Video in progress
What is the difference between checked and unchecked exceptions?
The compiler enforces checked exceptions (IOException, SQLException): you must either catch them or declare them with throws. Unchecked ones, which are RuntimeException and its descendants (NullPointerException, IllegalArgumentException), aren't required.
📖 Answer
The hierarchy:
Throwable
├── Error (OutOfMemoryError: usually not caught)
└── Exception (checked)
└── RuntimeException (unchecked)
// checked: the compiler requires handling
String read(Path p) throws IOException {
return Files.readString(p);
}
// unchecked: a programmer mistake
void setAge(int age) {
if (age < 0) throw new IllegalArgumentException("age < 0");
}
The logic is simple: checked is an external, expected problem (the file is missing, the network dropped) that the caller can react to. Unchecked is a bug in the code or an unrecoverable situation.
In practice, modern libraries (Spring, Hibernate) mostly use unchecked exceptions: checked ones work awkwardly with lambdas and have to be passed up through many layers with throws.
The worst habit is "swallowing" a checked exception with an empty catch. At the very least, log it or wrap it in an unchecked one and rethrow: throw new UncheckedIOException(e);.
Sign up to mark studied questions and save your progress.