Talk about the return statement in try catch finally in Java

  • 2020-04-01 04:38:10
  • OfStack

We know that the return statement is used in a certain method, one is used to return the result of the execution of the function, and the other is used to return a function of type void, just a return statement (return;). , which is used to end the execution of the method, that is, the statement after the return will not be executed, of course, in this case, there can be no other statement after the return statement.

The use of the return statement in the try-catch-finally statement encountered some problems

A code:


static int intc(){
int x =0;
try{
x=1;
return x;
}finally {
x = 3; 
}
}

Code 2: add a return statement to the finally statement in the above code


static int intc(){
int x =0;
try{
x=1;
return x;
}finally {
x = 3;
return x;
}
} 

Code 3:


static int intc(){
int x =0;
try{
x=1;
return x;
}finally {
x = 3;
return 0;
}
} 

So what are the results of the three methods?

Code 1: return 1;
Code 2: return 3;
Code 3: returns 0;

How does this work?

The reason is that when the Java virtual machine executes a method with a return value, it creates an area in the list of local variables to store the method's return value, and then reads the value from the area to return it when the return statement is executed.

Code 1 assigns 1 to the variable x in the try, then copies the value of the variable x to the area where the return value is stored. The return value area stores 1 and returns 1 when the return statement is executed.

In code 2, the same will be assigned to the variable x 1, and then copies the value of x to store the return value of area, the area of the return value has a value of 1, then jump to the finally statement, at this time will be 3 assignment to a local variable x, and then copies the value of x to store the return value of area, finally implement the return statement, read to the return of the values in the area is 3.

In code 3, the statement executed in the try is the same. After jumping to the finally statement, assign 3 to a local variable, and then assign 0 to the area where the return value is stored.


Related articles: