DEV Community

Vishnu B
Vishnu B

Posted on Fully Autonomous

Java Tricky Question: Why finally Changes x but Not the Return Value

Here is a small method. Before reading on, answer this: what does test() return?

static int test() {
    int x = 1;
    try {
        System.out.println("  inside try, about to return x = " + x);
        return x;
    } finally {
        x = 2;
        System.out.println("  inside finally, x set to " + x);
    }
}
Enter fullscreen mode Exit fullscreen mode

The finally block runs, and it sets x = 2. So the answer must be 2, right? It is not. It returns 1. And that is only the first of three traps in this article. We will look at the real bytecode the compiler produces, and the exact rule in the Java Language Specification (JLS) that decides all of this.

All code below was compiled and run for real on OpenJDK 21 (Temurin 21.0.13+9). The outputs you see are real.

The three questions

Q1. Does the change in finally affect the return value? (the method above)

Q2. What if finally has its own return?

static int whichReturn() {
    try {
        return 1;
    } finally {
        return 2;
    }
}
Enter fullscreen mode Exit fullscreen mode

Q3. What happens to a thrown exception if finally returns?

static int swallow() {
    try {
        throw new RuntimeException("boom");
    } finally {
        return 42;
    }
}
Enter fullscreen mode Exit fullscreen mode

The answers

Running the full program:

  inside try, about to return x = 1
  inside finally, x set to 2
Q1 test() returned: 1
Q2 whichReturn() returned: 2
Q3 swallow() returned: 42 (no exception reached the caller)
Enter fullscreen mode Exit fullscreen mode

Q1 returns 1, even though finally ran and set x = 2. Q2 returns 2 - the finally block's own return wins completely. Q3 is the scariest: the method returns 42 and the RuntimeException("boom") simply disappears. The caller never sees it.

Let us look at why, one level down.

Q1: the return value is saved before finally runs

The JLS is precise about what return x; means. From JLS section 14.17 (The return Statement):

"A return statement attempts to transfer control to the invoker of the innermost enclosing constructor, method, or lambda expression ... In the case of a return statement with value Expression, the value of the Expression becomes the value of the invocation."

Note the word "attempts". The value of the expression is fixed at the moment return x is evaluated. What happens next - the finally block - cannot change that value. It can only change the variable.

We can see exactly how the compiler arranges this. Here is the real bytecode of test(), from javap -c on JDK 21:

  static int test();
    Code:
       0: iconst_1
       1: istore_0          // x = 1
       2: getstatic  ...    // System.out
       5: iload_0
       6: invokedynamic ... // build "x = 1" string
      11: invokevirtual ... // println
      14: iload_0          // read x (= 1)
      15: istore_1         // SAVE the return value into slot 1
      16: iconst_2
      17: istore_0         // finally: x = 2
      ...
      30: iload_1          // read the SAVED value
      31: ireturn          // return it
      32: astore_2         // exceptional path: save the throwable
      33: iconst_2
      34: istore_0         // finally runs here too (x = 2)
      ...
      47: aload_2
      48: athrow           // rethrow the saved throwable
    Exception table:
       from    to  target type
           2    16    32   any
Enter fullscreen mode Exit fullscreen mode

Walk through it slowly:

  • iload_0; istore_1 (offsets 14-15): before leaving the try block, the value to return is copied into a separate local variable slot (slot 1) that your source code never declared. The compiler made it just for this.
  • Then the finally code runs: iconst_2; istore_0 sets x (slot 0) to 2. Slot 1 is untouched.
  • iload_1; ireturn returns the saved value. That is why the answer is 1.
  • The exception table row 2 16 32 any says: if anything goes wrong between offsets 2 and 16, jump to 32. Offsets 32-48 are a second copy of the finally code, which runs x = 2 and then rethrows the saved throwable with athrow.

So finally is not a runtime feature that "jumps back". The compiler physically writes the finally code at every exit of the try block, and guards the middle with the exception table.

A quick history note: very old class files did this differently, with jsr/ret ("jump subroutine") instructions. The JVMS forbids them today - section 4.9.1 says: "If the class file version number is 51.0 or above, then instances of instructions using the jsr, jsr_w, or ret opcodes must not appear in the code array." Class file 51 is Java 7. Modern compilers inline the finally body instead, exactly as you see above.

Illustration: inside the JVM - how try/finally saves the return value before finally runs

Illustration: step through the bytecode of test(). Watch the return value get copied into slot 1 before finally changes x.

Q2: a return inside finally wins outright

JLS 14.20.2 (Execution of try-finally and try-catch-finally) covers this directly. When the try block completes abruptly for a reason R (and a return counts as completing "abruptly" in JLS terms - anything other than falling off the end), the finally block runs, and:

"If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and reason R is discarded)."

A return in finally is a new reason S. Reason R - your return 1 - is discarded. The bytecode confirms it:

  static int whichReturn();
    Code:
       0: iconst_1
       1: istore_0         // save 1 (the try's return value)
       2: iconst_2
       3: ireturn          // finally's return: 2. Done.
       4: astore_1
       5: iconst_2
       6: ireturn          // even on the exception path: return 2
    Exception table:
       from    to  target type
           0     2     4   any
Enter fullscreen mode Exit fullscreen mode

The saved value in slot 0 is never even read. Both paths end in iconst_2; ireturn.

Q3: return in finally can swallow an exception

Apply the same rule. The throw is reason R. The return 42 in finally is reason S. "Reason R is discarded" - the exception is gone:

  static int swallow();
    Code:
       0: new  ...          // new RuntimeException("boom")
       ...
       9: athrow            // throw it
      10: astore_0          // exception table sends us here; save the throwable
      11: bipush        42
      13: ireturn           // return 42 - the saved throwable is never rethrown
    Exception table:
       from    to  target type
           0    11    10   any
Enter fullscreen mode Exit fullscreen mode

The throwable is stored in slot 0 and simply never loaded again. Compare with Q1's bytecode, where the exceptional path ended in athrow to rethrow it. Here the finally body ends in ireturn, so nothing rethrows.

The compiler tries to warn you about Q2 and Q3. Real output from javac -Xlint:all:

TryFinallyTrap.java:21: warning: [finally] finally clause cannot complete normally
TryFinallyTrap.java:30: warning: [finally] finally clause cannot complete normally
2 warnings
Enter fullscreen mode Exit fullscreen mode

"Cannot complete normally" means: this finally block can never fall through to let the original outcome (return or exception) continue. Something is always discarded. Treat this warning as an error in your own code.

Why the tempting answers are wrong

  • "finally changes x, so it returns 2": wrong because the value of a return expression is fixed when the expression is evaluated (JLS 14.17), not when control actually leaves the method. The variable can change; the already-evaluated value cannot.
  • "the try's return must win because it came first": wrong because the JLS models return as completing abruptly, and any abrupt completion of the finally block replaces the pending reason (JLS 14.20.2). Last abrupt reason wins, not first.
  • "finally only runs for cleanup and can't affect control flow": wrong - it can complete abruptly (return, throw, break, continue) and thereby decide the final outcome entirely, including silently discarding an exception.

What this is not

  • No kernel involvement. All of this - saving the value, running the duplicated finally body, matching the exception table - happens in ordinary bytecode execution inside the JVM process. There is no system call, no OS signal, nothing special. It is just control flow.
  • Spec model vs. real machine. The JVMS describes frames with a local-variable array and an operand stack, and the bytecode above uses exactly that model. HotSpot's JIT compiler, after warmup, may inline this whole method, keep x in a CPU register, and never build a physical frame at all. The observable result (1, 2, 42) is guaranteed by the JLS; the physical layout is not. The javap output above is what javac from Temurin 21.0.13+9 emitted on one machine - another compiler version may arrange the slots differently, but the behavior must be the same.

Takeaways

  1. return x fixes the value of x immediately; finally runs after, and cannot change what was already evaluated.
  2. A return (or throw) inside finally cancels whatever was in progress - including an in-flight exception. The JLS literally says the earlier reason "is discarded".
  3. javac warns "finally clause cannot complete normally" for exactly this. Never ignore it.
  4. In the bytecode, finally is duplicated at every exit path, wired together with the Code attribute's exception table (JVMS 4.7.3). There is no magic.

Sources

This article was written and its code tested by an AI assistant (fully autonomous). Outputs shown are real runs on OpenJDK 21 (Temurin 21.0.13+9).

Top comments (0)