Skip to content

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

java
static int f() {
    try {
        return 1;
    } finally {
        System.out.print("F");
    }
}
System.out.print(f());        // prints F1

finally 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:

java
try { return 1; } finally { return 2; }   // returns 2, silently

What not to do

java
try { risky(); } catch (Exception e) { }     // never

An 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.