Execution of a return statement in a try Catch finally statement in Java (summary version)

Source: Internet
Author: User

Here you see try > But one thing is for sure, the contents of the finally block are executed before the return statement in the try, and if there is a return statement in the Finall statement block, it is returned directly from finally. This is also the reason why the return in finally is not recommended. Here are a few things to look at.

Situation one (there is no return in return,finally in try):

 Public classTrytest { Public Static voidMain (string[] args) {System.out.println (test ()); }     Private Static intTest () {intnum = 10; Try{System.out.println ("try"); returnnum + = 80; }Catch(Exception e) {System.out.println ("error"); }finally{            if(Num > 20) {System.out.println ("num> 20: "+num); } System.out.println ("Finally"); }        returnnum; }}

The output results are as follows:

Trynum>20:90finally90

Analysis: apparently "return num + = 80" was split into "num = num+80" and "return num" two statements, the line executes the "num = num+80" statement in the try, saves it, and before "return num" executes in try, The statement in finally is executed before the 90 is returned.

Case two (both try and finally have return):

 Public classTrytest { Public Static voidMain (string[] args) {System.out.println (test ()); }     Private Static intTest () {intnum = 10; Try{System.out.println ("Try"); returnnum + = 80; }Catch(Exception e) {System.out.println ("Error"); }finally{            if(Num > 20) {System.out.println ("NUM>20:" + num);} System.out.println ("Finally"); return100; }    }}

The output results are as follows:

trynum>20:90finally100

Analysis: The return statement in a try is also split, and finally the return statement executes before the return statement in the try, so that return in the try is "overwritten" and is no longer executed.

Execution of a return statement in a try Catch finally statement in Java (summary version)

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.