Return Statement in try-catch-finally in java, catchreturnfinally
Some questions are raised when using the return statement in the try-catch-finally statement.
Code 1:
static int intc(){ int x =0; try{ x=1; return x; }finally { x = 3; } }
Code 2: add the return Statement to the finally statement of 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; } }
What are the execution results of these three methods?
Code 1: return 1; Code 2: return 3; Code 3: Return 0;View Code
What is the principle?
The reason is that when the Java virtual machine executes a method with a return value, it creates a region in the local variable list to store the return value of the method, when the return statement is executed, the value is read from this region and returned.
In code 1, assign a value of 1 to variable x in try, copy the value of variable x to the region where the returned value is stored, and the region where the returned value is stored is 1. When a return statement is executed, one is returned.
In code 2, 1 is also assigned to the variable x, and then the value of x is copied to the region where the returned value is stored. At this time, the value of the returned region is 1, and then jumps to the finally statement, assign 3 to the local variable x, copy the value of x to the region where the returned value is stored, and run the return statement. The value in the returned region is 3.
In code 3, the statements executed in try are the same. After jumping to the finally statement, assign 3 to the local variable, and then assign 0 to the region where the returned value is stored, finally, execute the return statement. The value in the returned region is 0, so 0 is returned.