Exception is also divided into runtime exceptions (runtime Exception) and checked exceptions (Checked Exception).
Case 1:try{} catch () {}finally{} return;
Execute in normal order.
Case 2:try{return;} catch () {} finally{} return;
The program executes code in the try block before return (including expression operations in the return statement);
Then execute the finally block and finally execute the return in try;
The return statement after the finally block is no longer executed.
Case 3:try{} catch () {return;} finally{} return;
The program executes the try first, and if an exception is encountered to execute a catch block,
There are exceptions:
Executes the code in the catch before return (including the expression operation in the return statement), and then executes all the code in the finally statement,
Finally executes the return in the catch block. The return statement after the finally block is no longer executed.
No exception:
Executes the try again and finally executes the last return statement.
Case 4:try{return;} catch () {} Finally{return;}
The program executes code in the try block before return (including expression operations in the return statement);
Then execute the finally block, because there is a return in the finally block and exit early.
Case 5:try{} catch () {return;} Finally{return;}
The program executes the code in the Catch block before return (including the expression operation in the return statement);
Then execute the finally block, because there is a return in the finally block and exit early.
Case 6:try{return;} catch () {return;} Finally{return;}
The program executes code in the try block before return (including expression operations in the return statement);
Exception: Executes the code in the Catch block before return, including the expression operation in the return statement;
Then the finally block is executed because there is a return in the finally block and exits early.
No exception: Then the finally block is executed, because there is a return in the finally block and exits early.
The print result is 2.
Based on the previous analysis, in the TRY statement block, when the return statement is executed, the results to be returned are ready, and then the program goes to finally execution. Before you go, try to put the results to be returned in a different local variable from the X, after the finally, and then take out the return results, so even if the variable x in finally is changed, it will not affect the return result.