The Plain Picture#
A supervisor who says: "Try running this job. If the part-shortage alarm goes off, do this instead. And whatever happens, switch off the machine at the end."
The Real Names#
try {
// code that might throw
} catch (NumberFormatException e) {
// runs only if a NumberFormatException (or subclass) was thrown in the try block
} catch (IOException | IllegalStateException e) {
// multi-catch: either type
// ...
} finally {
// ALWAYS runs: after the try finishes, after a catch, even if a return happens
}A
catchblock handles exceptions of its type and all its subclasses (polymorphism, Object-Oriented Programming Ch 4).Catch blocks are checked top to bottom; the first matching one runs. So put specific types before general ones — the compiler rejects a general
catch (Exception e)placed before a specific one it would hide.finallyis for clean-up that must happen no matter what.
Under the Hood#
try {
int[] a = new int[2];
a[5] = 1;
} catch (ArrayIndexOutOfBoundsException | NullPointerException e) {
System.out.println("caught: " + e.getClass().getSimpleName());
} finally {
System.out.println("finally runs");
}
// caught: ArrayIndexOutOfBoundsException
// finally runsDoes finally always run? Almost always: after normal completion, after a caught exception, after an uncaught one, even after return.
The exceptions: System.exit() is called, the JVM crashes or is killed (SIGKILL — Operating Systems Ch 12), or the thread runs
forever.
The finally + return trap:
static int weird() {
try {
return 1;
} finally {
return 2;
} // overrides the try's return — and would also swallow any exception!
}
System.out.println(weird()); // 2Never return from finally. (The compiler even warns about it.)
Gotchas
Swallowing exceptions —
catch (Exception e) { }with an empty body — hides bugs completely. At minimum log it; usually rethrow or handle it properly.Catching
Exceptiontoo broadly catches bugs you didn't expect (like NullPointerExceptions) and treats them as the error you did. Catch what you can actually handle.
Check yourself
4 questionsWhy must specific catch blocks come before general ones?
Show answerHide answer
The first matching block wins; a general one first would catch everything, making the specific one unreachable (the compiler rejects it).
When does finally not run?
Show answerHide answer
On System.exit, a JVM crash/kill, or if the try block never finishes.
What does weird() return and why is it dangerous?
Show answerHide answer
2 — the finally return overrides the try's; it would also discard any exception, hiding failures.
What's wrong with catch (Exception e) {}?
Show answerHide answer
It silently hides every failure, including bugs, so problems go unnoticed.