This is the 8th day of my participation in the First Challenge 2022. For details: First Challenge 2022.

Last time we looked at the order in which finally and return are executed from the point of view of bytecode instructions. Today we will look at the inevitable execution of finally in code!

Why must finally be executed

If you are careful, you will notice that lines 4-7 and 9-12 in the above bytecode instruction diagram are exactly the same, so why are there repeated instructions?

First, let’s analyze what these repeated instructions do. After analysis, we find that they are x = 2; return x; The bytecode instructions in finally code block. It is reasonable to suspect that if a catch block is added to the above code, the bytecode instructions corresponding to the finally block will also appear again.

public static int test2(a) {
    int x = 1;
    try {
        return x;
    } catch(Exception e) {
        x = 3;
    } finally {
        x = 2;
        returnx; }}Copy the code

After decompilation

Sure enough, repeated bytecode instructions appeared three times. Back to the original question, why do the bytecode instructions in finally code repeat themselves three times?

The JVM appended the finally bytecode instructions to try and catch, plus its own instructions, exactly three times to ensure that all exception paths and normal paths were executed in finally. This is why finally must be executed.

Will finally be executed?

Why do you need to do something else when you already said that the code in finally must execute? Please 👇

Under normal circumstances, it must be executed, but there are at least three cases in which it must not be executed:

  • tryThe statement is returned without being executedfinallyThe statement will not execute, so that showsfinallyA necessary but not sufficient condition for a statement to be executed is: correspondingtryStatement must be executed to;
  • tryIn the code blockSystem.exit(0);Such a statement, becauseSystem.exit(0);Is terminatedJVM, evenJVMIt’s all stopped,finallyIt certainly won’t be carried out;
  • Daemon threads exit when all non-daemon threads exitDaemon threadThe inside of thefinallyWhen the non-daemon thread terminates or exits,finallyCertainly not enforced;

See here, do you understand when finally is executed and when not executed? If you have different opinions or better idea, welcome to contact AH Q, add AH Q can also join the technical exchange group to participate in the discussion!