Card 03/ 10

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.

Throwable splits into Error, checked exceptions and unchecked ones
The three branches, what the compiler demands, and what each means
BranchCompiler demandsMeansExamples
ErrorNothingThe virtual machine is in troubleOutOfMemoryError, StackOverflowError
Checked ExceptionCatch it or declare itThe world did not cooperateIOException, SQLException
RuntimeExceptionNothingThe program has a bugNullPointerException, 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.