Try Finally Return Override Trap

A return inside finally overrides the value from try and silently discards an in-flight exception, so cleanup blocks must never complete abruptly.

JavaResilience

Code

snippet
public class FinallyTrap {

    static String withReturn() {
        try {
            return "try";
        } finally {
            // finally 的 return 覆盖 (override) try 已给出的返回值,这是 JLS 定义的 (trap)
            return "finally";
        }
    }

    static String swallows() {
        try {
            throw new IllegalStateException("boom");
        } finally {
            // finally 正常结束会吞掉正在传播的异常,调用方只看到返回值
            return "exception lost";
        }
    }

    public static void main(String[] args) {
        System.out.println("withReturn = " + withReturn());
        System.out.println("swallows   = " + swallows());
        System.out.println("rule       = never return in finally");
    }
}

Walkthrough

Try Finally Return Override Trap reduces to the class FinallyTrap and the functions withReturn, swallows and main.

IllegalStateException is thrown inside a try block — the matching handler clause, not any input check, decides what happens to it.

What to watch for

  • Nothing arrives from a registry; the language ships every API used.

Using it

The one signature to know: static String withReturn()

The run emits 3 labeled sections — withReturn =, swallows =, rule = never return in finally — one per step.

Start the program and main runs withReturn and swallows one after another.

Key statements

throw new IllegalStateException("boom");
return "exception lost";
return "finally";

Interactive Tools for This Topic

FAQ

Does the snippet validate its input?
No — the `IllegalStateException` is raised inside a `try` block: execution reaches it unconditionally, and the surrounding handler clause decides what catches it. There is no input check in the snippet.
What does Try Finally Return Override Trap print when run?
No setup needed: run the file and look for labeled lines like `withReturn =`, `swallows =`, `rule = never return in finally` in the output.