Try, catch, finally Execution Process
Keywords: Try, catch, finally Execution Process
Try {
// 1: code that throws an exception
// 2: Code
} Catch (){
// 3: Code
// 4: throw an exception
} Finally {
// 5: Code
}
// 6: Code
The first thing to be clear is that the finally statement block will be executed no matter whether the try throws an exception or not.
Caution 6 !!
The entire try, catch, and finally execution involves the following situations:
1: The try statement block does not throw an exception. In this case, the program will execute the code after try, finally, and finally blocks;
2: The try statement block throws an exception and the catch has a matching exception. When an exception is thrown in try, the remaining code in the try block will not be executed and will jump to the Catch Block.
There are two cases. First, the thrown exception is caught by the catch later. If the catch does not throw a new exception, the execution sequence is 1356.
; Second, if a new exception is thrown in catch, the sequence is 1345, and then the new exception is returned to the method caller. 6 is not executed.
;
3: An exception is thrown in the try statement block, but no exception can be matched in the catch later. Then, the try and finally statements 15 will be executed, and the exception will be returned to the method caller without executing 6
.
Summary:
If the exception cannot be caught, the statement after finally {} will not be executed, and finally {} will be executed.