Java – amazing output of try / catch / finally?

See English answers > behavior of return statement in catch and finally 6

public static void main(String[] args) {
    System.out.println(catcher());
}

private static int catcher() {
    try {
        System.out.println("TRY");
        thrower();
        return 1;
    } catch (Exception e) {
        System.out.println("CATCH");
        return 2;
    } finally {
        System.out.println("FINALLY");
        return 3;
    }
}

private static void thrower() {
    throw new RuntimeException();
}

I want to see this in the output:

TRY
CATCH
FINALLY
2

But surprisingly, the output is:

TRY
CATCH
FINALLY
3

I'm confused. Where to return the 2 declaration? Is the final return a bad practice?

Solution

In § 14.1 of jse7 language specification, return statement is defined as sudden termination If your finally block completes suddenly (your return), the try block ends for the same reason (as defined in § 14.20.2):

§ 14.1 [...] there is always a relevant reason for sudden completion, which is one of the following: [...] return without value [...] return with given value [...]

§14.20. 2 [...] if the finally block is suddenly completed because of S, the try statement is suddenly completed because of S (and the reason R is discarded) [...] (reason R is the result of capture)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>