Does a finally block always get executed in Java?

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

    A logical way to think about this is:

    1. Code placed in a finally block must be executed whatever occurs within the try block
    2. So if code in the try block tries to return a value or throw an exception the item is placed 'on the shelf' till the finally block can execute
    3. Because code in the finally block has (by definition) a high priority it can return or throw whatever it likes. In which case anything left 'on the shelf' is discarded.
    4. The only exception to this is if the VM shuts down completely during the try block e.g. by 'System.exit'

提交回复
热议问题