Topic 9 of 30 · Intermediate
Exception Handling
try/catch/finally, checked vs unchecked, custom exceptions.
Concept
Exceptions signal errors. Checked exceptions (IOException) must be caught or declared; unchecked ones (RuntimeException like NullPointerException) need not be.
finally always runs (except on System.exit). try-with-resources closes AutoCloseable resources automatically.
Errors (OutOfMemoryError) indicate serious JVM problems and shouldn't normally be caught.
Code (Java 21)
class InsufficientFundsException extends Exception {
InsufficientFundsException(String m) { super(m); }
}
static void withdraw(double bal, double amt) throws InsufficientFundsException {
if (amt > bal) throw new InsufficientFundsException("Balance too low");
}
try (var reader = new java.io.BufferedReader(new java.io.FileReader("data.txt"))) {
System.out.println(reader.readLine());
} catch (java.io.IOException e) {
System.out.println("Read failed: " + e.getMessage());
} finally {
System.out.println("done");
}Remember
- Throwable → Exception / Error.
- Catch specific exceptions first.
- Never swallow exceptions silently.
Interview questions
throw vs throws?
throw actually raises an exception object; throws in a method signature declares exceptions it may raise.
final vs finally vs finalize?
final: can't change/override/extend. finally: block that always runs after try. finalize: deprecated GC hook.
Lesson test
Take an 8-question test on “Exception Handling” — concepts, output prediction, bug spotting and interview questions.