What does a Java method return when both try and finally contain a return?
The finally block runs before the method actually returns, and a return inside finally overrides the earlier one, so the finally value wins. If finally only changes a variable, a primitive value already chosen for return is not affected.
Explain it simply
You hand a cheque to the clerk (the return value is noted down), but before you leave the counter the clerk must do the closing formalities (finally). If the formalities hand you a different cheque, that one replaces the first. If they only scribble on your copy of the original, the noted amount does not change.
Example
static int a() {
try { return 1; }
finally { return 2; } // overrides
}
static int b() {
int x = 1;
try { return x; } // value 1 is saved for returning
finally { x = 5; } // changes the variable, not the saved value
}
System.out.println(a()); // prints: 2
System.out.println(b()); // prints: 1What to say in the interview
"The return expression in try is evaluated first and its result is stored, then finally runs, then the method completes. A return in finally replaces the stored value and even swallows an exception that was in flight, which is why it is considered bad practice and compilers warn about it. For an object return, finally can still modify the object's contents because the reference is the same."
Common mistakes
- Returning from finally to be tidy. It silently discards exceptions.