Execution of return statement in try-catch-finally

Source: Internet
Author: User

Will it execute finally after the catch is return??
In Java, yes.
It is worth noting, however, that in the method where try-catch-finally is present, there are 4 locations where return can occur, in try, in catch, finally, after finally (statement block outside try-catch-finally).
In the case of return in all 4 positions (in fact it should be impossible, if there is a return in the previous 3 positions, then the return of the last position becomes unreachable code, the compilation will not pass), The return that will eventually be executed should be the return in the finally. That is, the return in the finally will overwrite the return from the other position.
However, when return is not present in Finally, and return is present in a catch, the statement in finally has an effect on the value of return in the catch, which is a bit complicated. See the following example:

int ret = 0;try{throw new Exception ();} catch (Exception e) {ret = 1; return ret;} finally{ret = 2;//return ret;} return ret;

There is no return in Finally, but the RET to return in the catch is assigned a value of 2. So what is the last value returned?
is 1. Why?
From debugging you can know that the assignment statement in finally is executed, and the next statement after executing this finally statement is the return in the catch, so why is 1 returned?
Looking at Java Language Specification 3.0, there seems to be no description of the situation.
In conjunction with some related articles on the web, it can only be inferred that, in this case (there is no return in the return,finally in the catch), the value of return has been determined before the finally execution.
Another notable note is that the last return (located outside of Try-catch-finally) is not executed.

Execution of return statement in try-catch-finally

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.