1. Regardless of whether there is an exception or an exception, the code in the final block will be executed; 2. When there is return in try and catch, finally will still be executed; 3. Finally is executed after the expression operation after return (at this time, the value after the operation is not returned, but the value to be returned is saved first, regardless of the code in finally, the returned value will not change, even if it is the previously saved value), so the function return value is determined before finally execution; 4. It is best not to include return in finally, otherwise the program will exit early, and the return value is not the return value saved in try or catch. Example:
Situation 1:try{} catch(){}finally{} return;
Apparently the procedure is carried out in order.
Situation 2:try{ return; }catch(){} finally{} return;
The program executes the code before return in the try block (including the expression operation in the return statement);
then execute the finally block, and finally execute the return in try;
finally block return, because the program has returned in try, so it is no longer executed.
Situation 3:try{ } catch(){return; } finally{} return;
The program executes try first, and if it encounters an exception, it executes the catch block,
If there is an exception, execute the code before return (including the expression operation in the return statement) in the catch, and then execute all the code in the final statement.
Finally, execute the return in the catch block. After finally, the code in 4 places will no longer be executed.
No exception: Execute try and then finally return.
Situation 4:try{ return; }catch(){} finally{return; }
The program executes the code before return in the try block (including the expression operation in the return statement);
Then execute the final block, because there is return in the finally block, so exit early.
Case 5:try{} catch(){return; }finally{return; }
The program executes the code before return (including expression operations in the return statement) in the catch block;
Then execute the final block, because there is return in the finally block, so exit early.
Situation 6:try{ return; }catch(){return; } finally{return; }
The program executes the code before return in the try block (including the expression operation in the return statement);
There is an exception: execute the code before return (including the expression operation in the return statement) in the catch block;
Then execute the finally block, because there is return in the finally block, so it exits early.
No exception: then execute the final block again, and exit early because there is return in the finally block.
Final conclusion: Any return statement in try or catch is executed before the final statement, if finally exists.
If there is a return statement in finally, then the program will return, so the return in finally will definitely be returned.
The compiler implements the return in finally as a warning.
|