Is there such case when in try\finally block the finally won't be executed?

不问归期 提交于 2019-12-17 16:56:06

问题


I'm studying for my test in Object Oriented Programming and I was wondering if there is any case what so ever that considering the following code:

try {
    do something
} catch (someException e) {

} finally {
    do something
}

the finally block will not execute?


回答1:


Yes. If you crash the Java VM or otherwise muck things up via native code, cause the program to terminate, or loop/wait infinitely inside the try block.

Those are the only three cases which will avoid executing the finally block.




回答2:


If you call System.exit(0) in the try. Or make something that makes the JVM quit or hang (like a deadlock). Otherwise - no.




回答3:


The Java Language Specification guarantees that finally is invoked before the try-statement completes.

The try statement might not complete for the usual reasons, which have been enumerated in Borealid's answer.




回答4:


The finally block will definitely get executed if the control comes out of the try or the catch block. If you some how manage to stop the control to come out of these blocks :

  • by writing exit statement, or

  • infinite loop etc.

then the finally block will not get executed. Generally we write the finally block for the "cleanup" purpose.



来源:https://stackoverflow.com/questions/3484353/is-there-such-case-when-in-try-finally-block-the-finally-wont-be-executed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!