Java exception mechanism -- try catch final execution sequence

Posted by echelon2010 on Fri, 21 Jun 2019 02:32:33 +0200

Introduction

There are many written interview questions about try catch final execution order. I have encountered them more than once while brushing the questions on Niuke. And I have missed them more than once. The details involved in them will produce a specious feeling if I don't know clearly each time I do the questions. This time, I have consulted a lot of relevant information, and basically talked about the order of try catch final execution. The shortcomings are welcome to be pointed out.

Try catch final execution order

Only in the following 4 cases will the final statement not be executed:

If System.exit(0) is executed in a try or catch statement.

(2) The jvm crashed before final execution.

(3) Execute a dead loop in the try statement.

(4) Power cut off.

In addition to the above four cases, final statements are executed, and there are the following principles when final statements are executed.

(1) Whether there is an exception or not, the code in the final block will be executed;

  public void demo1(){
        try {

          System.out.println(result);

        } catch (Exception e) {                     
            System.out.println(e.getMessage());
        }
         finally {            
                System.out.println("finally trumps. ");
            }
//The output results are as follows:
result
finally trumps .

The above code shows that if no exception occurs, try and finally blocks are executed sequentially.

(2) When there is a return in try and catch, final will still be executed;

public static int demo2() {
        try {
            return 0;
        }
        finally {
            System.out.println("finally trumps return.");
        }
    }
//Output results

finally trumps return.
0   

When there is no return statement in final, the return statement is executed after the try and final statements are executed.
(3) finally is performed after the expression operation after return (at this time, it does not return the value after the operation, but first saves the value to be returned, regardless of the code in final, the returned value will not change, even if it is the value previously saved), so the function return value is determined before final execution;

public static int demo3()
    {
         int i = 0;
            try {
                i = 2;
                return i;
            } finally {
                i = 12;
                System.out.println("finally trumps return.");
            }       
    }
//Output results
    finally trumps return.
    2

In this case, the final assignment of i is 12, but the return value of demo3 is still 2. That is to say, the final assignment of i does not change the return value of i. Here we need to talk about in detail, which involves the jvm mechanism. First, the bytecode of the above code is given and then the diagram is given.

public static demo3()I
    TRYCATCHBLOCK L0 L1 L2 
   L3
    LINENUMBER 12 L3
    ICONST_0
    ISTORE 0
   L0
    LINENUMBER 14 L0
    ICONST_2
    ISTORE 0
   L4
    LINENUMBER 15 L4
    ILOAD 0
    ISTORE 2
   L1
    LINENUMBER 17 L1
    BIPUSH 12
    ISTORE 0
   L5
    LINENUMBER 18 L5
    GETSTATIC java/lang/System.out : Ljava/io/PrintStream;
    LDC "finally trumps return."
    INVOKEVIRTUAL java/io/PrintStream.println (Ljava/lang/String;)V
   L6
    LINENUMBER 15 L6
    ILOAD 2
    IRETURN
   L2
    LINENUMBER 16 L2
   FRAME FULL [I] [java/lang/Throwable]
    ASTORE 1
   L7
    LINENUMBER 17 L7
    BIPUSH 12
    ISTORE 0
   L8
    LINENUMBER 18 L8
    GETSTATIC java/lang/System.out : Ljava/io/PrintStream;
    LDC "finally trumps return."
    INVOKEVIRTUAL java/io/PrintStream.println (Ljava/lang/String;)V
   L9
    LINENUMBER 19 L9
    ALOAD 1
    ATHROW

The bytecode above is rather long. Let's talk about it briefly. Actually, I'm here. http://blog.csdn.net/u013309870/article/details/72935274 This article describes in detail the execution process of the code in the method.

There are two variable areas in variable memory, one for storing the value of i, the top one, and the other for storing the return value. The above code executes to i=2; return i; assigns I to 2 first, and then executes the return statement. Instead of returning the result, the value of i=2 is saved to the return value variable area. When i=12 is executed, it returns to 2 of the return value address variable area in the variable.

(4) In final, it is better not to include return, otherwise the program will exit ahead of time, and the return value is not the return value saved in try or catch.

    public static int demo4() {
        int i = 0;
        try {
            return i;
        } finally {
            i = 12;
            System.out.println("finally trumps return.");
            return i;
        }
    }
    //Output results
    finally trumps return.
    12  

Why does it return to 12? Because the return statement in final is executed before the program executes the return statement in try, the return result is 12.

Classic interview questions

What is the output of the following title?

    public static int demo5() {
        try {
            return printX();
        }
        finally {
            System.out.println("finally trumps return... sort of");
        }
    }
    public static int printX() {

        System.out.println("X");
        return 0;
    }

Output results:

X
finally trumps return... sort of
0

The topic above contains a lot of money. When the program is executed sequentially, the printX () function is executed first. At this time, the return value 0 is obtained and saved to the corresponding region of variable to save the return value. At this time, the program executes the final statement because there is no return statement in the final statement, so the program returns the 0 of the return value area to the upper function.

Reference

https://stackoverflow.com/questions/65035/does-finally-always-execute-in-java
http://blog.csdn.net/u013309870/article/details/72935274
Deep understanding of advanced features and best practices of Java Virtual Machine (HD Version 2) JVM

Topics: Java jvm