This question already has an answer here:
- Does a finally block always get executed in Java? 46 answers
- Strange finally behaviour? 7 answers
I am confused about the try-finally execution when there exists return;
in the try block. In my understanding, the finally block will always be executed, i.e. before returning to the calling method. While considering the following simple code:
public class TryCatchTest {
public static void main(String[] args){
System.out.println(test());
}
static int test(){
int x = 1;
try{
return x;
}
finally{
x = x + 1;
}
}
}
The result printed is actually 1. Does this mean the finally block is not executed? Can anyone help me with it?
When you return from
try
block, the return value is stored on the stack frame for that method. After that the finally block is executed.Changing the value in the finally block will not change the value already on the stack. However if you return again from the finally block, the return value on the stack will be overwritten, and the new
x
will be returned.If you print the value of
x
in finally block, you will get to know that it is executed, and the value ofx
will get printed.Note: In case of a reference value being returned, the value of reference is stored on the stack. In that case, you can change the value of object, using that reference.
Suggested Read:
You are returning x before you exit try. I would do this:
The finally block is executed. The local variable is incremented. But the value of that local variable has already been copied for the return value.
From the Java Language Specification, 14.17: The return statement: