Appearance
Custom Exception
Common exceptions defined by the Java standard library include:
Exception
├─ RuntimeException
│ ├─ NullPointerException
│ ├─ IndexOutOfBoundsException
│ ├─ SecurityException
│ └─ IllegalArgumentException
│ └─ NumberFormatException
├─ IOException
│ ├─ UnsupportedCharsetException
│ ├─ FileNotFoundException
│ └─ SocketException
├─ ParseException
├─ GeneralSecurityException
├─ SQLException
└─ TimeoutException
When we need to throw exceptions in code, try to use the exception types defined by the JDK. For example, the argument check is illegal and should throw IllegalArgumentException
:
java
static void process1(int age) {
if (age <= 0) {
throw new IllegalArgumentException();
}
}
In a large project, new exception types can be customized, but it is very important to maintain a reasonable exception inheritance system.
A common approach is to customize a BaseException
as the "root exception" and then derive exceptions of various business types.
BaseException
needs to be derived from a suitable Exception
, and it is generally recommended to derive from RuntimeException
:
java
public class BaseException extends RuntimeException {
}
Exceptions of other business types can be derived from BaseException
:
java
public class UserNotFoundException extends BaseException {
}
public class LoginFailedException extends BaseException {
}
...
A custom BaseException
should provide multiple constructors:
java
public class BaseException extends RuntimeException {
public BaseException() {
super();
}
public BaseException(String message, Throwable cause) {
super(message, cause);
}
public BaseException(String message) {
super(message);
}
public BaseException(Throwable cause) {
super(cause);
}
}
The above construction methods actually copy RuntimeException
as it is. In this way, when an exception is thrown, you can choose the appropriate construction method. The IDE can quickly generate the construction method of the subclass based on the parent class.
Summary
When throwing an exception, try to reuse the exception types defined by the JDK;
When customizing the exception system, it is recommended to derive the "root exception" from RuntimeException
and then derive the business exception;
When customizing exceptions, you should provide multiple construction methods.