We know that return will end this method and return the specified value. And in try-catch-finally, it is executed regardless of the code in the try code block that has no exception in the finally. But what if the return is contained in a try or catch block in try-catch-finally?
Let's do another experiment:
1 Static intTXT () {2 Try{3@SuppressWarnings ("Unused")4 inta=5/0;5 7}Catch(Exception e) {8System.out.println ("Catch");9 return2;Ten}finally{ OneSystem.out.println ("finally"); A} - return3; -}
Demo
Look at the code above we know that in try "int a=5/0" is sure to error, then the program will go into the catch for exception handling but return a 2 in the catch using return, then finally the code in the end will still go? If the code in finally is gone, what is the return result?
Let's take a cut. The result of this method output:
We can see the finally block, even if the catch block has a return, he'll still be executed.
Let's start with another example.
1 Static intTXT () {2 Try{3 4 inta=5/0;5 6 7}Catch(Exception e) {8System.out.println ("Catch");9 return2;Ten}finally{ OneSystem.out.println ("finally"); A return3; -} - the}
Demo
How much is return returned then?
Let's see the results in a few words:
We can understand this: when we define a method with a return value type, the system automatically declares the memory address on the stack to hold the value returned by this method, which is why we define a method with a return value type, but no given return value is the cause of the compilation error! When the program executes the return of the catch block, the value after return is stored in the pre-declared stack memory and does not end this method and then executes the code of the finally block. But the finally block also has the return keyword so the value saved in the pre-declared stack memory becomes the value after the return in the finally block. This method ends again because there is no code block enforced after the Finall block.
The above content for personal understanding if there are deficiencies please the great God to correct me.
Thinking:
1 Static int txt () { 2 int a=1; 3 try { 4 5 a++ ; 6 return A; 7 8 }finally{ 9 ++a; 11} }
Demo
What is the return value of this method.
The order in which return in Java is executed in Try-catch