Card 03/ 10
Checked vs Unchecked Exceptions, and Errors
One exception will not compile until you handle it; another is just as fatal and the compiler says nothing.
Everything that can be thrown in Java descends from Throwable, which splits three ways. Checked exceptions must be caught or declared, because they report the outside world failing. Unchecked exceptions, subclasses of RuntimeException, report bugs and need neither. Errors report the JVM, the Java Virtual Machine running the program, itself in trouble.
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.
"Declare" means adding throws IOException to the method's signature, which passes the obligation to every caller. The catch-or-declare rule is checked by the compiler, which is what makes these exceptions "checked".
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.
← → move through sections and cards