The return in try... catch... finally has always been a hot test site for the interview. It can be divided into the following situations:
1. If a finally statement exists and return exists in try, the finally content is executed before the return statement is executed.
Package com. and. java. demo; public class test {public static void main (String [] args) {System. out. println (new test (). test ();} public String test () {try {System. out. println ("try {...} "); return" try ";} catch (Exception e) {System. out. println ("catch {...} "); return" catch ";} finally {System. out. println ("finally {...} ");}}}
Output:
try{...}finally{...}try
2. On the basis of 1, if a return statement exists in finally, return in the try code block is blocked (not executed), that is, when return is encountered in try, will first execute the content in finally (including the return statement in finally ).
Package com. and. java. demo; public class test {public static void main (String [] args) {System. out. println (new test (). test ();} public String test () {try {System. out. println ("try {...} "); return" try ";} catch (Exception e) {System. out. println ("catch {...} "); return" catch ";} finally {System. out. println ("finally {...} "); return" finally ";}}}
Output:
try{...}finally{...}finally
Problems:
You must have mastered these two cases. But there is another situation that I cannot understand. In general, close data in finally (such as file, input/output stream, and database close, if we modify the value to be returned in finally, will it reflect the final result? (As you can see from the above explanation, when there is a return in the try, it will not be executed immediately, it will first execute the content in finally, and then execute return ).
Package com. and. java. demo; public class test {public static void main (String [] args) {System. out. println (new test (). test ();} public String test () {String result = ""; try {result = "try"; return result;} catch (Exception e) {result = "catch"; return result;} finally {result = "finally ";}}}
Imagine if it will output "try" or "finally?
Output:
Try
Only try is output, but in finally, the value of result is changed?
Further improvements are made to determine whether the value assignment statement in finally is executed.
Package com. and. java. demo; public class test {public static void main (String [] args) {System. out. println (new test (). test ();} public String test () {String result = ""; try {result = "try"; return result;} catch (Exception e) {result = "catch"; return result;} finally {System. out. println ("t1->" + result); result = "finally"; System. out. println ("t2->" + result );}}}
Output:
t1->tryt2->finallytry
From the output result, we can see that the value assignment statement in finally is executed, but in the return result, why is it not changed? (Currently, I haven't figured it out yet. I hope you can give me some advice)