14 · 32 · 5 min
When something goes wrong
An exception is how a method says "I cannot do what you asked" to a caller that may be several frames away.
Checked or unchecked
Checked exceptions are conditions the caller could anticipate and recover from: a missing file, a refused connection, a timeout. The compiler forces a decision because there is one to make.
Unchecked exceptions are programming errors: null where a value was required, an index out of range. Catching them is usually wrong, because the fix belongs in the code that called badly.
finally
static int f() {
try {
return 1;
} finally {
System.out.print("F");
}
}
System.out.print(f()); // prints F1finally runs on every exit: normal completion, a return, or a thrown exception. The return value is computed and held, finally runs, then control leaves.
The dangerous version returns from inside finally, which discards the original value and any exception in flight:
try { return 1; } finally { return 2; } // returns 2, silentlyWhat not to do
try { risky(); } catch (Exception e) { } // neverAn empty catch turns a failure into a wrong answer, delivered confidently. If there is genuinely nothing to do, the comment explaining why is not optional.