All topics
library
intermediate

Exception Hierarchy & Handling Strategy

Navigate the exception hierarchy, choose between checked and unchecked, and adopt modern exception handling patterns.

Java has two categories of exceptions:

Checked exceptions = a certified letter (you must sign for it and acknowledge receipt). Unchecked exceptions = a text notification (delivered, but you might ignore it). Errors = a house fire alarm (you can't ignore it, and you shouldn't try to 'handle' it yourself).

Key Concepts

1
Checked exceptions (extend Exception, not RuntimeException): must be declared in throws clause or caught. The compiler enforces handling. Examples: IOException, SQLException, ParseException.
2
Unchecked exceptions (extend RuntimeException): don't require declaration or catching. Represent programming errors. Examples: NullPointerException, IllegalArgumentException, IndexOutOfBoundsException.
3
Errors (extend Error): serious JVM problems. Don't catch these. Examples: OutOfMemoryError, StackOverflowError.
4
The debate: - Checked exceptions force callers to handle failures → safer but verbose - Unchecked exceptions are cleaner → but failures can be silently ignored - Modern Java and most frameworks favor unchecked: Spring wraps all checked exceptions in unchecked ones (DataAccessException wraps SQLException) - Lambdas and streams don't work well with checked exceptions (functional interfaces don't declare throws)
5
Best practices: - Use unchecked for programming errors (invalid arguments, illegal state) - Use checked (sparingly) for recoverable conditions the caller must handle (file not found, network timeout) - Never catch Exception or Throwable broadly — it swallows errors you didn't intend to catch - Include the original exception as the cause: new CustomException("message", cause)