I have code:
class Test {
public static void main(final String [] args) {
System.out.println(foo());
}
private static int foo() {
int a = 0;
try {
++a;
return a;
} finally {
a = 10;
}
}
}
I can't uderstand why 1 is printed.
JVM is a stack-based machine. It push and pop value onto the stack. I decompiled
Test
class, to understand how it work.Simply...you have not mentioned return a in or after final block. Final block is executed in the end and value of a is set to 10, but you have not coded to return this new value! Try below code to get your expected output:
This happens because the
finally
block of a try..catch..finally runs after the code within thetry..catch
has completedYou are assigned the value in
finally
and before that you returned intry
The code in finally always executes,but you are already returned the value in
try
.Now
a
value is10
, after thereturn
. Though not a good practice, Just for demo.Now it
return
's10
.Edit:
Your doubt : Why unreacable error not coming ?
in
try-catch-finally
the blocks are different. Do the same in same block and see.Edit2
From java language specification of try-catch-finally :
The value of
a
is incremented and returned in thetry
block itself. Post thisreturn
, the value ofa
is re-assigned in thefinally
block. And that is the reason, why it prints 1.Quoting from the docs. This should help you understand it more clearly.
Compiling finally
Compilation of a try-finally statement is similar to that of try-catch. Prior to transferring control outside the try statement, whether that transfer is normal or abrupt, because an exception has been thrown, the finally clause must first be executed. For this simple example:
The compiled code is:
There are four ways for control to pass outside of the try statement:
In the above code, value returned will be 1 because, finally will not update the value returned in the try block.
The above code will return the value as 10, because, the value is returned from finally again.