Does a finally block always get executed in Java?

前端 未结 30 2144
逝去的感伤
逝去的感伤 2020-11-21 07:24

Considering this code, can I be absolutely sure that the finally block always executes, no matter what something() is?

try         


        
30条回答
  •  不要未来只要你来
    2020-11-21 07:33

    NOT ALWAYS

    The Java Language specification describes how try-catch-finally and try-catch blocks work at 14.20.2
    In no place it specifies that the finally block is always executed. But for all cases in which the try-catch-finally and try-finally blocks complete it does specify that before completion finally must be executed.

    try {
      CODE inside the try block
    }
    finally {
      FIN code inside finally block
    }
    NEXT code executed after the try-finally block (may be in a different method).
    

    The JLS does not guarantee that FIN is executed after CODE. The JLS guarantees that if CODE and NEXT are executed then FIN will always be executed after CODE and before NEXT.

    Why doesn't the JLS guarantee that the finally block is always executed after the try block? Because it is impossible. It is unlikely but possible that the JVM will be aborted (kill, crash, power off) just after completing the try block but before execution of the finally block. There is nothing the JLS can do to avoid this.

    Thus, any software which for their proper behaviour depends on finally blocks always being executed after their try blocks complete are bugged.

    return instructions in the try block are irrelevant to this issue. If execution reaches code after the try-catch-finally it is guaranteed that the finally block will have been executed before, with or without return instructions inside the try block.

提交回复
热议问题