What we normally call Try-catch,throw are all about the anomalies that can be checked.
For exception classifications, see Exceptions in Java
Once a catch statement catches an exception, it enters the exception's processing code until the end of the processing, the entire Try-catch statement ends, and the other catch, even if there is an exception, does not match the entry.
Another example of the order of execution is as follows:
publictest1(){ true; try { System.out.println("in try"); return b; finally{ false; System.out.println("in finally , b:"+b); } }
publicinttest2(){ int0; try { thrownew Exception(); catch (Exception e) { ++b; System.out.println("in catch , b:"+b); return b; } finally{ ++b; System.out.println("in finally, b:"+b); //return b; } }
Test1 Output Results:
In try
In Finally, B:false
Returns True
Test2 Output Results:
1
2
Returns 1
Test2 reason: When an exception is thrown, enter Catch,++b, at which point B is 2. Before return, due to the existence of finally, we first enter Finally,++b, at which point B is 3, but for the value B to be returned, before entering finally, the JVM copies a b before the return of the catch. Then another B enters finally and is modified. Finally come out from finally, continue to walk return, which is returned is still before the reservation of B.
Note that only the return will enter the finally, so only the return variable will have this phenomenon.
Likewise applies to test1.
Summarize:
1. The statement in the finally block executes regardless of whether it is an exception;
2. When there is a return statement in a try or catch block, the statements in the finally block are still executed;
3. The statements in the finally block are executed before the function returns, but the function return value is determined before the statement executes in the finally block;
Add: General finally is not recommended to write the return statement, although not error, but very insecure.
Try-catch-finally in Java