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 the code, try to use the exception types defined by JDK. For example, parameter checking is invalid and should throw IllegalArgumentException
:
static void process1(int age) {
if (age <= 0) {
throw new IllegalArgumentException();
}
}
In a large project, you can customize new exception types, but it is very important to maintain a reasonable exception inheritance system.
A common practice is to customize one BaseException
as the "root exception", and then derive exceptions of various business types.
BaseException
Exception
Deriving from a suitable one is required , and it is generally recommended to RuntimeException
derive from:
public class BaseException extends RuntimeException {
}
Exceptions of other business types can be BaseException
derived from:
public class UserNotFoundException extends BaseException {
}
public class LoginFailedException extends BaseException {
}
...
Custom ones BaseException
should provide multiple construction methods:
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 are actually copied as they are RuntimeException
. In this way, when an exception is thrown, an appropriate construction method can be selected. The IDE can quickly generate the construction method of the subclass according to the parent class.
summary
When throwing an exception, try to reuse the exception types defined by 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, multiple construction methods should be provided.