Does a finally block always get executed in Java?

前端 未结 30 1636
逝去的感伤
逝去的感伤 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:44

    Yes, finally will be called after the execution of the try or catch code blocks.

    The only times finally won't be called are:

    1. If you invoke System.exit()
    2. If you invoke Runtime.getRuntime().halt(exitStatus)
    3. If the JVM crashes first
    4. If the JVM reaches an infinite loop (or some other non-interruptable, non-terminating statement) in the try or catch block
    5. If the OS forcibly terminates the JVM process; e.g., kill -9 on UNIX
    6. If the host system dies; e.g., power failure, hardware error, OS panic, et cetera
    7. If the finally block is going to be executed by a daemon thread and all other non-daemon threads exit before finally is called

提交回复
热议问题