Java basic interview question: there is a return statement in try {}, so will the code in finally {} following this try be executed? When will the code be executed, before or after return ?,
Package com. swift; public class Try_Catch_Finally_Test {public static void main (String [] args) {/** try {} contains a return statement, so will the code in finally {} following this try be executed, when will it be executed, before or after return? */System. out. println ("execute return without returning the value first, save the value for temporary storage, wait until finally execution is complete and then return the saved value" + new Try_Catch_Finally_Test (). test ();} static int test () {int x = 1; try {return ++ x;} finally {++ x; System. out. println ("finally first executed, return last executed" + x );}}}
Return also exists in finally, and finally return in finally
Package com. swift; public class Try_Catch_Finally_Test {public static void main (String [] args) {/** try {} contains a return statement, so will the code in finally {} following this try be executed, when will it be executed, before or after return? */System. out. println ("execute return without returning the value first, save the value for temporary storage, wait until finally execution is complete and then return the saved value" + new Try_Catch_Finally_Test (). test ();} static int test () {int x = 1; try {return ++ x;} catch (Exception e) {e. printStackTrace (); return ++ x;} finally {++ x; System. out. println ("finally first executed, return last executed" + x); return ++ x ;}}}
Some people say that the return statement is executed twice and finally is executed in the middle. This is understandable and may be easy to memorize.
But I think return is executed after finally. After finally is executed, return the returned value to the call. Note that the returned value is not the final value, instead, return will return the returned value, but the value temporarily saved because it cannot be returned in finally. There is an interruption here.