The execution order of try catch finally with return, catchfinally
Background:
Yesterday, a friend went out for an interview and encountered the following question: "C # Is there a return in catch and is it still executed in finally ?"
Personal practice summary:
1,Code in finally blocks will be executed no matter what an exception occurs..
2,When return exists in try and catch, finally will still execute.
The specific case is as follows (Here we use a function without return values for verification ):
3,If the value is passed, the value changed in finally has no effect on the value returned by return in try or catch block.;If it is a reference type parameter (address transfer or object), changing the value in finally will affect return..
Case study:
Reference case -- array type:
Value case -- int type:
Thinking: If the string type is a reference type, Will its return value be affected by finflly? Let's take a look at the case ----- in fact, the string and int types are the same and won't be affected by finally:
Thinking: what is the impact of adding return in finally? There is a picture with the truth:
It can be seen that return is not allowed in finally, otherwise the compilation will fail.
The program has a try-catch-finally structure and a return after finally. If there is an exception in the try, how does finally and return be executed?
The execution sequence of try, catch, and finally when there is no exception in try --- finally
If an exception occurs in try, the execution sequence is try --- catch --- finally.
If there is no exception in try and return exists in try, the normal execution order is try ---- finally --- return.
If there is an exception in try and return exists in try, the normal execution order is try ---- catch ---- finally --- return.
In short, finally is always executed!
Java try catch finally return execution sequence
If the execution sequence is normal, try finally return.
When an exception occurs and no program block exists in catch, the order is try catch finally return.
When an exception occurs and the catch contains a statement that jumps out of the program block, it is a try catch (before execution) finally catch (Execution jumps out)
Let me give you a reference program.
Paste the main function and execute it to see the sequence.
System. out. println ("begin"); List list = new ArrayList <Integer> (); list. add (1); for (int I = 0; I <= 2; I ++) {try {System. out. println (list. get (I);} catch (Exception e) {System. out. println (e); continue;} finally {System. out. println ("stop");} System. out. println ("out ");}