Java code:
public class Test1 {
public static void Main (string[] args) {
int a=method1 ();
SYSTEM.OUT.PRINTLN ("result----a=" +a);
}
public static int method1 () {
int a=0;
try {
A=1;
System.out.println ("Try----a=" +a);
return A;
} catch (Exception e) {
a=2;
System.out.println ("catch----a=" +a);
return A;
}finally{
A=3;
SYSTEM.OUT.PRINTLN ("finally----a=" +a);
return A;
}
}
}
Output Result:
Try----a=1
Finally----a=3
Result----A=1
Regardless of whether there are any return,finally code in the try, it will execute. Add a breakpoint can be seen, execute to return in the try, then go to the Finally, finally after the execution of a return to the try return statement execution returned. Finally, the statement executes, but the result of the final return is the value of a in the try, not the value in the Finally, because the result of return in the try execution has been staged, and then to execute the code in Finally, At this point the code in the finally does not affect the final return value of the method, and finally the code returns to return to the try after execution, returning the staged result (official document). But if there is a return in Finally, the return value is the value in finally.
For example, uncomment the return statement in the finally
Output Result:
Try----a=1
Finally----a=3
Result----A=3
About Java try/catch/finally/has a return when the execution process