Handling Exceptions
Handling Exceptions
This domain tests the exception hierarchy, checked versus unchecked exceptions, try/catch/finally, try-with-resources, and the throw and throws keywords. Expect questions on control flow and on which catch blocks compile.
Hierarchy and rules
Throwablesplits intoErrorandException;RuntimeExceptionis unchecked, while otherExceptionsubclasses are checked. Checked exceptions must be caught or declared withthrows.catchblocks are tested in order; a superclass catch after a subclass catch is unreachable and fails to compile. Multi-catch (catch (IOException | SQLException e)) cannot include related types, and the variable is effectively final.finallyruns aftertry/catchon normal or exceptional exit, but not if the JVM exits viaSystem.exitor crashes. Areturninfinallyoverrides earlier returns and exceptions.- Try-with-resources requires
AutoCloseableresources; they close in reverse order, and close exceptions are suppressed. throwthrows one object;throwsdeclares possible exceptions in a method signature. An overriding method may narrow checked exceptions but not add broader ones.
Worked example
public static void main(String[] args) {
try {
System.out.println("A");
throw new RuntimeException();
} catch (Exception e) {
System.out.println("B");
} finally {
System.out.println("C");
}
}
The try prints A, the exception is caught, B prints, and finally always runs, so C prints. Output is A B C on separate lines.
Traps
- Catching
Exceptiondoes not catchError. - A checked exception thrown in a method without
throwsis a compile error even if callers catch it. catch (Exception | RuntimeException e)is illegal because the alternatives are related.- Returning from
finallycan silently discard an exception. - A resource declared before the
tryis not automatically closed by try-with-resources.