The execution time of the finally statement

Source: http://coderbee.net/index.php/java/20110321/456
Comment: Semantically finally executes after
return Although I knew that in the try finally statement, even if there is a return statement in the try block, the finally statement will The return statement is executed before the execution, but the execution order of the return expression and the finally statement is unknown.

public class Test {
    public static int a() {
        int i = 0;

        try {
            i++;
            return ++i;

        } finally {
            i++;
System.out.println("finally:" + i);
        }
    }

    public static void main (String[] args) {
        System.out.println(a());
    }
}
The output of this statement is 2 instead of 3.
When executing to return ++i;

The jvm executes ++i first, stores the result 2 in a temporary variable, and then executes ++i in the finally statement, so although the final value of i is 3, the value returned by the method is 2.

In fact, the previous understanding is not wrong, because return ++i; is a compound statement, which is equivalent to:

    int j = ++i; 
    return j; 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327037383&siteId=291194637