When Java is return in try, finally does not execute?

Source: Internet
Author: User

In a Java method, after a return in a try, the later finally executes?
The test code is as follows:

publicintprint(){    try    {        System.out.println("try");        return1;    }    catch(Exception e){        return0;    }    finally{        System.out.println("finally");    }    }

See the results directly:

Try
Finally

Reason:
The finally statement executes before the return.

What if we add a return to finally?
The test code is as follows:

 Public classMain { Public Static void Main(string[] args) {System. out. println (print ()); } Public Static int Print(){Try{System. out. println ("Try");return 1; }Catch(Exception e) {return 0; }finally{System. out. println ("Finally");return 2; }    }}

The results are as follows:

Try
Finally
2

Deep Understanding:
An analysis of the depth of the finally statement block in Java

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Does Java return after a try and finally does not execute?

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.