DT Dream Factory pen exam review 1 ---- is finally executed after return or before ?, ---- Finallyreturn
1 package test; 2 3 public class TestFinally {4 public static void main (String [] args) {5 Demo = new demo (); 6 TestFinally tf = new TestFinally (); 7 String result = tf. fun1 (demo); 8 System. out. println (result); 9 System. out. println (demo. str); 10} 11 private String fun1 (Demo demo) {12 try {13 demo. str + = "1"; 14 return fun2 (demo); 15} finally {16 demo. str + = "2"; 17} 18} 19 private String fun2 (Demo demo) {20 try {21 demo. str + = "3"; 22 return demo. str; 23} finally {24 demo. str + = "4"; 25} 26} 27} 28 class Demo {29 String str = ""; 30}View Code
Execution result:
13
1342
The answer I wrote is result = 1234 demo. str = 1234. In my memory, finally is the keyword for exception capture, and the finally code block will certainly be executed. However, I am not very clear about the execution process. I used to think that if return is returned, that is, the function is over, it will be executed finally before return. Therefore, the above error result is written. The correct result shows that if a finally code block exists after the return statement is executed, the finally code block will be executed after the return statement is executed. The result is result = 12 demo. str = 1324.
Further, how will return be executed in finally?
(1)
1 package test; 2 3 public class TestFinally {4 public static void main (String [] args) {5 Demo = new demo (); 6 TestFinally tf = new TestFinally (); 7 String result = tf. fun1 (demo); 8 System. out. println (result); 9 System. out. println (demo. str); 10} 11 12 private String fun1 (Demo demo) {13 try {14 demo. str + = "1"; 15 return fun2 (demo); 16} finally {17 18 demo. str + = "2"; 19} 20} 21 22 private String fun2 (Demo demo) {23 try {24 demo. str + = "3"; 25 return demo. str; 26} finally {27 demo. str + = "4"; 28 return demo. str; // added return statement 29} 30} 31 32 33} 34 class Demo {35 String str = ""; 36}View Code
Execution result:
134
1342
(2)
1 package test; 2 3 public class TestFinally {4 public static void main (String [] args) {5 Demo = new demo (); 6 TestFinally tf = new TestFinally (); 7 String result = tf. fun1 (demo); 8 System. out. println (result); 9 System. out. println (demo. str); 10} 11 12 private String fun1 (Demo demo) {13 try {14 demo. str + = "1"; 15 return fun2 (demo); 16} finally {17 demo. str + = "2"; 18 return demo. str; // added return statement 19} 20} 21 22 private String fun2 (Demo demo) {23 try {24 demo. str + = "3"; 25 return demo. str; 26} finally {27 demo. str + = "4"; 28} 29} 30 31 32} 33 class Demo {34 String str = ""; 35}View Code
Execution result:
1342
1342
If return exists in finally. If a finally code block exists after the return statement is executed, the finally code block will be executed after the return statement is executed, the return in finally overwrites the return result in the try code block.