Is the Java finally statement executed before or after return?

There are many people on the Internet discussing the exception capture mechanism in Java. Will the finally statement in the try...catch...finally block be executed? Many people say no, of course their answers are correct. After my experiments, there are at least two cases where the finally statement will not be executed:

(1) The try statement is not executed. For example, it returns before the try statement, so the finally statement will not be executed. This also shows that the necessary but not sufficient condition for the finally statement to be executed is that the corresponding try statement must be executed. arrive.

(2) There is a statement like System.exit(0); in the try block, System.exit(0); is to terminate the Java virtual machine JVM, even the JVM is stopped, everything is over, of course, the finally statement does not will be executed.

The finally statement is executed after the return statement of the try is executed and before the return returns.

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

public static int test1() {
int b = 20;
try {
System.out.println("try block");
return b += 80;
}
catch (Exception e) {
System.out.println("catch block");
}
finally {
System.out.println("finally block");
if (b > 25) {
System.out.println("b>25, b = " + b);
}
}
return b;
}
}public class FinallyTest1 {
    public static void main(String[] args) {
        System.out.println(test1());
    }


    public static int test1() {
        int b = 20;
        try {
            System.out.println("try block");
            return b += 80; 
        }
        catch (Exception e) {
            System.out.println("catch block");
        }
        finally {
            System.out.println("finally block");
            if (b > 25) {
                System.out.println("b>25, b = " + b);
            }
        }  
        return b;
    }
}

The result of running is:

try block
finally block
b>25, b = 100
100
It means that the return statement has been executed and then the finally statement is executed, but it does not return directly, but returns the result after the finally statement is executed.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325749052&siteId=291194637