Checked vs.
Unchecked Exceptions
Learn how Java divides exceptions into two categories: those the compiler enforces and those that surface only at runtime.
What Is an Exception?
An exception is an event that disrupts the normal flow of a program. When something goes wrong, Java creates an exception object that contains information about the error: its type, a message, and where it occurred.
The Throwable Hierarchy
Two Categories of Exceptions
The Compiler Rule
For checked exceptions, the compiler enforces a strict contract: every method that might throw a checked exception must either catch it or declare it in its signature.
The Formal Classification Rule
Common Checked Exceptions
Common Unchecked Exceptions
Predictable vs. Preventable
| Checked | Unchecked | |
|---|---|---|
| Extends | Exception | RuntimeException |
| Compiler enforced? | Yes | No |
| When it happens | External failures you cannot prevent | Bugs you can prevent |
| Must catch or declare? | Yes | No |
| Typical examples | IOException, SQLException | NullPointerException, ArithmeticException |
Handling with try-catch
The try block contains code that might throw. The catch block handles the exception if it occurs. This is one of the two ways to satisfy the compiler for checked exceptions.
Declaring with throws
Instead of catching the exception yourself, you can declare it in the method signature with the throws keyword. This pushes the responsibility to handle it to whoever calls your method.
How to Decide: Step by Step
Example 1: Reading a File
Example 2: Null Reference
This compiles perfectly. The compiler has no complaint because NullPointerException is unchecked. The crash happens only at runtime.
Example 3: Multiple Exceptions
Common Mistakes
Summary Comparison
| Feature | Checked | Unchecked |
|---|---|---|
| Parent class | Exception | RuntimeException |
| Compile-time check | ✓ Required | ✕ Not required |
| Cause | External conditions | Programming errors |
| Handle or declare? | Must do one | Optional |
| Best practice | try-catch or throws | Prevent with code logic |
| Examples | IOException, SQLException | NullPointerException, ArithmeticException |
Question 1 of 5
Which of the following is a checked exception in Java?
Question 2 of 5
What happens if you write code that could throw a checked exception but do not catch or declare it?
Question 3 of 5
A NullPointerException is unchecked because it:
Question 4 of 5
Consider the following method signature:
public void saveRecord(String data) throws SQLException { ... }
Which statement about this method is correct?
Question 5 of 5
Which is the best practice for handling an unchecked exception like ArrayIndexOutOfBoundsException?