Checked and Unchecked Exceptions
Checked exceptions must be caught or declared with throws because they represent expected outside failures, while unchecked RuntimeExceptions usually signal bugs and are not enforced by the compiler.
Decide which failures require a declared handling strategy and which indicate other problems.
Brew Bar's program loads the day's menu from a file. One day the file is missing, and the program has to cope. Another day a developer calls a method on a null drink. Java treats these two failures very differently: the compiler forces you to plan for the first, but not the second.
The rule
Checked means the compiler makes you handle it or declare it.
All exceptions descend from Throwable, in three branches:
Throwable
├── Error serious JVM trouble: do not catch
│ └── OutOfMemoryError
└── Exception checked, except for one branch:
├── IOException checked
└── RuntimeException unchecked
├── NullPointerException
├── IllegalArgumentException
│ └── NumberFormatException
└── ArithmeticExceptionChecked exceptions are every Exception that is not a RuntimeException. They stand for problems outside your program's control that a careful program should expect, such as a missing file or a dropped network connection. For these, the compiler insists on one of two things:
// Option 1: handle it here
String loadMenu(Path file) {
try {
return Files.readString(file);
} catch (IOException e) {
return "Menu unavailable";
}
}
// Option 2: declare it, and let the caller decide
String loadMenu(Path file) throws IOException {
return Files.readString(file);
}The throws IOException clause is part of the method's contract. Anyone calling loadMenu now faces the same choice.
Unchecked exceptions are RuntimeException and its subclasses. They usually mean a bug in the code, such as a null where an object was expected or an index past the end. The compiler does not force you to catch them; the right fix is usually to correct the code.
Errors, such as OutOfMemoryError, signal that the JVM itself is in trouble. Ordinary programs should not try to catch them.