Custom exceptions are needed in test script writing, and it is often easy to create custom exception classes in Java. It can be a checked or unchecked exception. Here is a simple example to check the creation of custom exceptions in Java.
- How do I create a custom exception class
- Throws a custom Java exception
- Catch custom exceptions
- Check the output
Java custom exception
The following classes are simple Java classes that create custom exceptions.
package com.fun.base.exception;
public class FailException extends Exception {
private static final long serialVersionUID = -7041169491254546905L;
public FailException(a) {
super("FunTester");
}
protected FailException(String message) {
super(message); }}Copy the code
To create an exception:
- To create a
Java
class - extension
Exception
class - call
super()
There are other constructors in the Exception class. This is a basic example of creating custom exceptions. This is the most common way.
Trigger a custom exception
In the example above, we created a custom FailException. Now, let’s throw this exception in the Java code example.
public static void fail(String message) {
throw new FailException(message);
}
Copy the code
Steps to throw an exception:
- Create an instance of FailException
- Throw an exception using the throw keyword
- Declare exceptions in methods using the throws keyword
Demo
/** * Convert json object ** based on parsed content@param content
* @return* /
private static JSONObject getJsonResponse(String content, JSONObject cookies) throws FailException {
JSONObject jsonObject = new JSONObject();
try {
if (StringUtils.isEmpty(content)) FailException.fail("Response is empty!");
jsonObject = JSONObject.parseObject(content);
} catch (JSONException e) {
jsonObject = getJson("content=" + content, "code=" + TEST_ERROR_CODE);
logger.warn("The response body is not in JSON format, it has been automatically converted to JSON format!");
} finally {
if(cookies ! =null && !cookies.isEmpty()) jsonObject.put(HttpClientConstant.COOKIE, cookies);
returnjsonObject; }}Copy the code
- Solemnly declare: The public account “FunTester” first, welcome to pay attention to the exchange, prohibit the third party to reprint. More original articles:18 original albums by FunTesterPlease contact for cooperation
[email protected]
.
Hot article selected
- Function This interface is used to test albums
- Performance Testing Topics
- Graphic HTTP brain map
- Programming thinking for everyone
- The Definitive Guide to Java Performance
- Selenium parallel testing best practices
- How do I maintain automated tests
- About the UI test plan
- Software testing outsourcing