4.2 Checked vs Unchecked Exceptions
← Back to Chapter 4: Exception Handling
Java is unique among mainstream languages in distinguishing between Checked and Unchecked exceptions at the compiler level.
Difference Between Checked and Unchecked Exceptions
Checked exceptions are checked by the compiler.
Unchecked exceptions are exceptions that occur during runtime and does not cheched by the compiler.
| Dimension | Checked Exceptions | Unchecked Exceptions (RuntimeException) |
|---|---|---|
| Superclass | Direct subclasses of Exception (except RuntimeException) | Subclasses of java.lang.RuntimeException |
| Compiler Enforcement | Strict: Must handle with try-catch OR declare with throws | None: Compiler does not force handling or declaration |
| Root Cause | Unpredictable external environmental conditions | Programmer error, violated preconditions, invalid state |
| Typical Examples | IOException, SQLException, ParseException | NullPointerException, IndexOutOfBoundsException |
2. When to Use Each in Real Systems
When to Use Checked Exceptions:
- When a failure is anticipated and the calling code can reasonably recover or provide a fallback.
- Example:
FileNotFoundException—prompting the user to select an alternate file path.
When to Use Unchecked Exceptions:
- When the error represents an unrecoverable logic bug or violated contract that requires developer intervention.
- Example: Passing a negative argument to a method that requires a positive number (
IllegalArgumentException). - Modern Enterprise Trend (Spring Boot, Hibernate): Modern frameworks wrap low-level checked exceptions into unchecked runtime exceptions (e.g. Spring converts checked
SQLExceptioninto uncheckedDataAccessException) to avoid polluting method signatures with verbosethrowsclauses.