Checked vs Unchecked Exceptions
In Java, exceptions are broadly classified into two categories: Checked Exceptions and Unchecked Exceptions. Understanding the difference is crucial for writing robust and compiler-friendly Java code.
1. Checked Exceptions
Checked exceptions are exceptions that are checked by the compiler at compile-time.
If a method throws a checked exception, the compiler forces the programmer to either:
- Handle the exception using a
try-catchblock. - Declare the exception using the
throwskeyword in the method signature.
If neither of these is done, the code will not compile.
Characteristics
- They represent conditions outside the immediate control of the program (e.g., I/O errors, network issues, database problems).
- All classes that inherit from
ExceptionexceptRuntimeExceptionand its subclasses are checked exceptions.
Examples
IOException(e.g., trying to read a file that doesn't exist)SQLException(e.g., database connection fails)ClassNotFoundException
2. Unchecked Exceptions
Unchecked exceptions are exceptions that are not checked by the compiler at compile-time. They occur at runtime.
The compiler does not force the programmer to handle or declare unchecked exceptions. It is up to the programmer to write logical code to avoid them (e.g., checking if an object is null before using it).
Characteristics
- They typically represent programming errors, logic flaws, or improper use of an API.
- Classes that inherit from
RuntimeException(and its subclasses) are unchecked exceptions.
Examples
NullPointerException(e.g., calling a method on anullreference)ArithmeticException(e.g., dividing an integer by zero)ArrayIndexOutOfBoundsException(e.g., accessing an invalid index in an array)
3. Errors
Errors are also unchecked by the compiler, but they are conceptually different from unchecked exceptions.
Characteristics
- Errors indicate severe problems that a reasonable application should not try to catch.
- They are derived from the
Errorclass. - They are typically thrown by the JVM itself.
Examples
OutOfMemoryErrorStackOverflowError
Quick Comparison
Here is a summary comparing the three categories:
| Feature | Checked Exceptions | Unchecked Exceptions | Errors |
|---|---|---|---|
| Checked at Compile-Time? | Yes | No (Checked at Runtime) | No (Checked at Runtime) |
| Superclass | Exception | RuntimeException | Error |
| Recovery | Recoverable | Recoverable | Irrecoverable |
| Cause | External conditions (Files, Network, DB) | Programming flaws (Logic errors, bad inputs) | Severe system or environment failures |
| Handling Requirement | Mandatory (try-catch or throws) | Optional | Should not be handled |
[!TIP] Best Practice: Use checked exceptions for recoverable conditions and unchecked exceptions for programming errors.