As mentioned in the Java Core Technology Volume One: When the finally clause contains a return statement (of course, the design is not allowed to throw an exception in the finally block or execute a return statement, I don't understand why the Java designer does not disable this form in syntax). There will be an unexpected result. Assume that a return statement is used to exit from a try statement block. The contents of the finally clause are executed before the method returns. If there is also a return statement in the finally clause, the return value overrides the original return value.
However, the author does not mention that the return statement in finally will not only overwrite the original return value, but also "eat" the exception thrown in the catch clause. The test code is as follows:
Import java.io.*;p ublic class returninfinally{public static void Main (string[] args) {Try{boolean i=test1 (); System.out.println ("End of Try Test1");} catch (Exception ex) {System.out.println ("Catch Exception in Main ()");} Finally{system.out.println ("Finally in Main ()");} Boolean j=test2 (); System.out.println ("j=" + j);} private static Boolean Test1 () throws Exception{try{throw new Exception ("Exception Thrown by Test1 ()");} catch (Exception ex) {System.out.println ("Catch Exception in Test1 ()"), throw ex;//re-throw exception}finally{return true;// Thrown exception is return "eat" off}}private static Boolean Test2 () {Try{return false;} Finally{return true;}}}
The result of the operation is:
Catch exception in Test1 () End of the Try test1finally in Main () j=true
Java finally contains the return statement