Checked exceptions: exceptions that are checked at compile time. 所以需要在方法上throws异常,或者用try-catch来处理异常,不然编译器会报错。Checked exceptions表示在正常work flow之外的错误。
// throws keyword
private static void checkedExceptionWithThrows() throws FileNotFoundException {
File file = new File("not_existing_file.txt");
FileInputStream stream = new FileInputStream(file); // constructor抛出的异常
}
// try-catch
private static void checkedExceptionWithTryCatch() {
File file = new File("not_existing_file.txt");
try {
FileInputStream stream = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
The Exception class is the superclass of checked exceptions. Therefore, we can create a custom checked exception by extending Exception:
public class IncorrectFileNameException extends Exception {
public IncorrectFileNameException(String errorMessage) {
super(errorMessage);
}
}
Unchecked exceptions: 反应的是程序的logic error。比如你要除以0,会抛ArithmeticException。
private static void divideByZero() {
int numerator = 1;
int denominator = 0;
int result = numerator / denominator;
}
Java是不会在compile-time verify unchecked exception
The RuntimeException class is the superclass of all unchecked exceptions. Therefore, we can create a custom unchecked exception by extending RuntimeException:
public class NullOrEmptyException extends RuntimeException {
public NullOrEmptyException(String errorMessage) {
super(errorMessage);
}
}
Checked vs Unchecked exception:
If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.
For example, before we open a file, we can first validate the input file name. If the user input file name is invalid, we can throw a custom checked exception:
if (!isCorrectFileName(fileName)) {
throw new IncorrectFileNameException("Incorrect filename : " + fileName );
}
In this way, we can recover the system by accepting another user input file name. However, if the input file name is a null pointer or it is an empty string, it means that we have some errors in the code. In this case, we should throw an unchecked exception:
if (fileName == null || fileName.isEmpty()) {
throw new NullOrEmptyException("The filename is null or empty.");
}
Exception Hierarchy