How does the JVM guarantee execution of the finally block?

前端 未结 2 391
生来不讨喜
生来不讨喜 2021-01-31 18:56

This question is aimed at how the JVM is able to guarantee the execution of a finally block (provided the JVM doesn\'t crash and the thread is not interrupted o

2条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-31 19:24

    I believe this blog clearly describes the internal:

    If a method has defined a try-catch or a try-finally exception handler then an Exception Table will be created. This contains information for each exception handler or finally block including the range over which the handler applies, what type of exception is being handled and where the handler code is.

    When an exception is thrown the JVM looks for a matching handler in the current method, if none is found the method ends abruptly popping the current stack frame and the exception is re-thrown in the calling method (the new current frame). If no exception handler is found before all frames have been popped then the thread is terminated. This can also cause the JVM itself to terminate if the exception is thrown in the last non-daemon thread, for example if the thread is the main thread.

    Finally exception handlers match all types of exceptions and so always execute whenever an exception is thrown. In the case when no exception is thrown a finally block is still executed at the end of a method, this is achieved by jumping to the finally handler code immediately before the return statement is executed.

提交回复
热议问题