Checked and Unchecked Exceptions
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.
The shortcut
Ask "Could perfect code still hit this?" A missing file can happen to perfect code, so it is checked: handle or declare. A null drink means the code is wrong, so it is unchecked: fix the bug rather than wrapping it in try.
Look at the declaration
Files.readStringdeclaresthrows IOException.
Drills
Answer fast — trust the rule.
Which of these is a checked exception?
A method calls Files.readString(path) with no try block and no throws clause. What happens?
NumberFormatException extends IllegalArgumentException, which extends RuntimeException. Is it checked?
Code keeps throwing NullPointerException because a drink is sometimes null. What is the best response?
Remember
- Checked means the compiler makes you handle it or declare it with
throws. - Ask "could perfect code still hit this?" Yes → checked; no → a bug to fix.
- Traps: catching Errors, and swallowing a bug's RuntimeException instead of fixing it.
