Considering this code, can I be absolutely sure that the finally
block always executes, no matter what something()
is?
try
I tried the above example with slight modification-
public static void main(final String[] args) {
System.out.println(test());
}
public static int test() {
int i = 0;
try {
i = 2;
return i;
} finally {
i = 12;
System.out.println("finally trumps return.");
}
}
The above code outputs:
finally trumps return.
2
This is because when return i;
is executed i
has a value 2. After this the finally
block is executed where 12 is assigned to i
and then System.out
out is executed.
After executing the finally
block the try
block returns 2, rather than returning 12, because this return statement is not executed again.
If you will debug this code in Eclipse then you'll get a feeling that after executing System.out
of finally
block the return
statement of try
block is executed again. But this is not the case. It simply returns the value 2.