Checked vs Unchecked Exceptions
Java splits exceptions into two enforcement categories: checked exceptions, which the compiler forces you to deal with, and unchecked exceptions, which it does not. Understanding which category an exception falls into tells you exactly what the compiler will and will not let you get away with.
Checked Exceptions
This does NOT compile
import java.io.FileReader;
import java.io.IOException;
public class UncaughtCheckedDemo {
public static void main(String[] args) {
FileReader reader = new FileReader("data.txt"); // compile error!
}
}Fixed: catch it, or declare it
import java.io.FileReader;
import java.io.IOException;
public class CaughtCheckedDemo {
public static void main(String[] args) {
try {
FileReader reader = new FileReader("data.txt");
} catch (IOException e) {
System.out.println("Could not open file: " + e.getMessage());
}
}
}Unchecked Exceptions
Compiles fine — no catch or throws required
public class UncheckedDemo {
public static void main(String[] args) {
int[] numbers = {1, 2, 3};
System.out.println(numbers[10]); // compiles fine, fails at runtime
}
}Side-by-Side Comparison
Aspect | Checked | Unchecked |
Base classes | Exception (excluding RuntimeException) | RuntimeException and Error |
Compiler enforcement | Must catch or declare with throws | No enforcement at all |
Typical meaning | An anticipated, recoverable condition | A programming bug or invariant violation |
Examples | IOException, SQLException | NullPointerException, IllegalArgumentException, ArithmeticException |