Mastery
Mastery/Java/F. Exceptions
T2 · intermediate depth

finally silently swallowing a return/exception from try

Same trap as Python's finally, expressed in Java: a return inside finally always wins, discarding whatever the try block was about to return -- and if an exception was actively propagating out of try, that exception is discarded too, with no trace. javac actually warns about this ([finally] finally clause cannot complete normally) -- one of the few warnings worth never suppressing.

java
static int returnOverride() {
    try {
        return 1;
    } finally {
        return 2;   // silently discards the try's return value
    }
}

static int swallowsException() {
    try {
        throw new RuntimeException("this exception vanishes without a trace");
    } finally {
        return 99;   // the exception never propagates -- gone
    }
}

System.out.println("finally overriding return: " + returnOverride());
System.out.println("finally swallowing an exception entirely: " + swallowsException());

Interview angle

The same "find the bug" exercise as the Python version, testing whether a candidate's mental model of finally is "runs after, doesn't change the outcome" (wrong) versus "can completely override the outcome, including silently discarding an active exception" (correct) — a surprisingly common misconception even among experienced developers who've never specifically been shown this.

In the industry

javac itself warns about this ([finally] finally clause cannot complete normally), and any serious static analysis setup (SpotBugs, Error Prone) flags a return/break/continue/throw inside finally as a near-certain bug. Unlike some warnings that are routinely ignored, this one is treated as close to a hard error in most style guides, precisely because the failure mode (a silently swallowed exception) is so hard to debug after the fact — there's no trace left to follow.