Java finally contains the return statement

Source: Internet
Author: User
Tags finally block throw exception

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.