Card 03/ 10
All 10 cards
ConceptDifficulty: Beginner1 min
Checked, Unchecked, and the Errors You Are Not Meant to Catch
One method will not compile until you handle what it throws. Another throws something just as fatal and the compiler says nothing at all. The difference is a branch of a class hierarchy.
| Branch | Compiler demands | Means | Examples |
|---|---|---|---|
Error | Nothing | The virtual machine is in trouble | OutOfMemoryError, StackOverflowError |
Checked Exception | Catch it or declare it | The world did not cooperate | IOException, SQLException |
RuntimeException | Nothing | The program has a bug | NullPointerException, IllegalArgumentException |
The line is about whose fault it is. A file that is missing is not a mistake in your code, so the compiler insists you say what happens. Dereferencing null is a mistake in your code, and no amount of catching fixes it, so the compiler leaves you alone.
So when you write your own exception, the branch you extend is a statement about the caller. Extend Exception when a reasonable caller could recover; extend RuntimeException when the only fix is a code change.