Document directory
public class JVMTest {public static void main(String[] args) {System.out.println("aa:" + aa());}public static int aa() {int a = 1;int b = 10;try {System.out.println("abc");return a;} finally {a = 2;System.out.println("a:" + a);}}}
The running result is:
ABC
A: 2
AA: 1
It can be seen that in the try statement, when the return statement is executed, the results to be returned are ready. At this time, the program is switched to finally for execution.
Before forwarding, try to store the results to be returned in local variables different from A. After finally execution, retrieve the returned results,
Therefore, even if variable A is changed in finally, the returned results are not affected.
However, what if return a is added to the finally clause?
The execution result is as follows:
Compiling 1 source file to E: \ sun \ insidejvm \ build \ Classes
E: \ sun \ insidejvm \ SRC \ jvmtest. Java: 37: Warning: finally clause cannot complete normally
}
1 warning
Compile-single:
Run-single:
ABC
A: 2
AA: 2
Test 1:
public static int test1(){ int i = 1; try { return ++i; } finally { ++i; Console.WriteLine("finally:" + i); }}static void Main(string[] args){ Console.WriteLine("Main:" + test1());}
Result:
Finally: 3
Main: 2
Test 2:
public static int test2(){ int i = 1; try { throw new Exception(); } catch { return ++i; } finally { ++i; Console.WriteLine("finally:" + i); }}static void Main(string[] args){ Console.WriteLine("Main:" + test2());}
Result:
Finally: 3
Main: 2
Test 3:
public static int test3(){ try{} finally { return 1; }}
Result:
Compilation error. The control cannot leave the finally Clause body.
Conclusion:
1. The statements in the Finally block are executed no matter the exception occurs;
2. When a return statement exists in a try or catch block, the statements in the Finally block will still be executed;
3. The statements in the Finally block are executed only after the return statement is executed, that is, the return value of the function is determined before the statements in the Finally block are executed;
4. The Finally block cannot contain the return statement.
Conclusion: The finally statement is executed before return. The finally statement does not change the fixed return value,
Finally cannot add a return statement. If an exception occurs, first find whether a processor can handle the exception. Then finally.