Points to note about try-catch-finally

First is the full version of try-catch-finally
 
1. If there is an exception in try, catch catches the exception and finally executes it.

2. If there is no exception in try, finally execute.

3. There is an exception in try, return in catch, and finally execute.

4. There is an exception in try, return in catch, and finally try to change the variable returned in catch, but it is found that it cannot be changed.

Principle: The finally statement has an execution detail. If there is a return statement in the try or catch statement, the return statement is executed after the finally statement is executed, but the finally cannot change the return value. The execution process is that before the return i; statement in the catch is executed, the return value i will be saved in a temporary variable, and then the finally statement will be executed, and finally the catch will return to the temporary variable, and the modification of i in finally will not will be returned.

 

5. There is an exception in try, return in catch, and return in finally.

6. An exception thrown in finally will overwrite the previous exception.

7. You can use finally to return the normal value, and the exception in the catch will not be thrown.

The catch statement is not required. The result of running without the catch statement is similar to the previous 7 cases.

8. The return in try does not throw an exception, and finally executes.

9. Return throws an exception in try, and finally executes.

10. Finally try to change the variable returned in try and find that it cannot be changed. The principle is the same as in the previous 4.

11. Use finally to override the exception thrown in try.

12. You can use finally to return the normal value, so that the exception in try will not be thrown.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324727829&siteId=291194637