Try this piece of code. Why does getValueB() return 1 instead of 2? After all, the increment() function is getting called twice.
public class ReturningFromFinally
{
public static int getValueA() // This returns 2 as expected
{
try { return 1; }
finally { return 2; }
}
public static int getValueB() // I expect this to return 2, but it returns 1
{
try { return increment(); }
finally { increment(); }
}
static int counter = 0;
static int increment()
{
counter ++;
return counter;
}
public static void main(String[] args)
{
System.out.println(getValueA()); // prints 2 as expected
System.out.println(getValueB()); // why does it print 1?
}
}
Yes, but the return value is determined before the second call.
The value returned is determined by the evaluation of the expression in the return statement at that point in time – not “just before execution leaves the method”.
From section 14.17 of the JLS:
Execution is then transferred to the
finallyblock, as per section 14.20.2 of the JLS. That doesn’t re-evaluate the expression in the return statement though.If your finally block were:
then that new return value would be the ultimate result of the method (as per section 14.20.2) – but you’re not doing that.