I recently saw someone asking questions in the jar.
I found myself making a mistake for the first time.
So I verified it again.
Draw a conclusion to reach out to the party.
1. The finally block and the outermost layer have only one return statement. Otherwise, a compilation error occurs. (Catch Block does not affect this conclusion)
---- The try block and the outermost layer have only one return. Otherwise, a compilation error occurs. (Sometimes, catch blocks must also have return)
---- Return can be written in finally instead of the outer layer, but a warning is reported (marked as yellow ). (Try block, catch Block does not affect this conclusion)
2. When finally has a return, it will run away from finally's return regardless of the exception.
---- The try block has return. If there is no exception (do not enter the catch Block), the return of the finally block goes to finally; otherwise, the return of the try.
-------- The outer layer does not go. In fact, when the return to try is run, finally is executed to return the return of try, but finally also has return, so it is equivalent to a half-path.
---- The try block has return. When an exception occurs (entering the catch Block), the return of the finally block goes to finally. Otherwise, the return of the catch is used.
-------- I explained the same as above. When I got to finally, I ran halfway.
Verification Code:
[Java]
/**
* Try, catch, and finally return in JAVA
* @ Author qian. xu
*
*/
Public class MyReturn {
Public String test (){
Int [] a = new int [2];
Try {
// For (int I = 0; I <2; I ++) {// normal system
For (int I = 0; I <3; I ++) {// exception system
// If I = 2 is executed, an error is returned.
A [I] = I;
}
System. out. println ("try block execution completed ");
// Return "I am the return of the try block ";
} Catch (Exception e ){
System. out. println ("catch Block executed ");
Return "I am the return of the catch Block ";
} Finally {
System. out. println ("finally block executed ");
Return "I am the return of the finally block ";
}
// Return "I am the last return ";
}
/**
* @ Param args
*/
Public static void main (String [] args ){
// TODO Auto-generated method stub
MyReturn myReturn = new MyReturn ();
System. out. println (myReturn. test ());
}
}