Return statement in try-finally block in java
What will this program print out?
Result is 2.
We know that finally gets ALWAYS executed (unless jvm died). So, out method returns 1 and then, finally is called. So it returns 2 and overrides previous value. Question is why?
The answer is in the approach used by jvm for method calling.
When a method is called, jvm creates a stack frame. When a method is done, it’s stack frame is removed and the result is pushed to the caller’s stack.
Returning an integer from a message call is represented by ireturn byte code instruction (hex code #AC). Obviously, it’s not possible to push more than one result to a caller’s stack - it would break indexing and raise a runtime error. To protect against this failure, the compiler actually removes first return statement and keeps byte code instruction for second one only.
Here is javap result for the example from above:
Basically, if you have a return statement in a finally block - it will be the only one return point in the compiled code.