It was previously thought that the function would return the result and terminate it as soon as it was executed to the return statement, but this was wrong because there was a special case.
Grasp the following principles to completely solve the "when try, catch, finally encounter return" problem.
Principle: 1. The code in the finally statement block is bound to execute, and the code in the CATCH block executes only if an exception occurs.
2. The function will not terminate after executing the return statement in the try block, and will continue to execute the catch (executed only when the exception is thrown), and finally the block of the end statement.
3, the function must ensure that there is a unique return value
Description: If a return statement is included in a try, at least one of the catch blocks and finally blocks must contain a return statement. Or try in a throw new Exception (); Throws an exception, then the catch and finally have at least one return statement. Because the try block assumes that an exception occurred, and the code in the try block executes smoothly, or throws an exception. If you only include a return statement in a try block, there is no guarantee that the function has a return value (if the try throws, the return statement will not execute). So in order to ensure that the function has a return value, Java enforces the requirement principle.
4, the return statement has the highest priority, and the return statement with only one of the two in the try and catch block is executed. To ensure that the function has only one return value, the highest priority value is returned.
Here are some examples of the above three principles
?
12345678910111213141516171819202122232425 |
public class TestReturn {
public static void main(String[] args) {
TestReturn t1 =
new TestReturn();
int k =
0
;
System.out.println(t1.test1(k));
}
public int test1 (
int k) {
try {
k = k +
1
;
System.out.println(
"try"
+ k);
return k;
}
catch (Exception e) {
k = k +
2
;
System.out.println(
"catch"
+ k);
return k;
}
finally {
k = k +
3
;
System.out.println(
"finally"
+ k);
return k;
}
}
}
|
Results:
Try1
Finally4
4
Description: After executing the output in try, it does not return because its return priority is not the highest, and continues to execute the FINALLY statement block and returns
?
1234567891011121314151617181920212223 |
public class TestReturn {
public static void main(String[] args) {
TestReturn t1 =
new TestReturn();
int k =
0
;
System.out.println(t1.test1(k));
}
public int test1 (
int k) {
try {
throw new Exception();
}
catch (Exception e) {
k = k +
2
;
System.out.println(
"catch"
+ k);
return k;
}
finally {
k = k +
3
;
System.out.println(
"finally"
+ k);
return k;
}
}
}
|
Results:
Catch2
Finally5
5
Order of execution between java_try,catch,finally return