在try\finally块中是否有这样的情况,finally不会被执行?
我正在学习面向对象编程的测试,我想知道是否存在考虑以下代码的情况:
try {
do something
} catch (someException e) {
} finally {
do something
}
finally
块不会执行?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的。如果您使 Java VM 崩溃或通过本机代码搞砸了事情,则会导致程序终止,或在
try
块内无限循环/等待。这是唯一可以避免执行
finally
块的三种情况。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.如果您在
try
中调用System.exit(0)
。或者做一些让 JVM 退出或挂起的事情(比如死锁)。否则 - 不。If you call
System.exit(0)
in thetry
. Or make something that makes the JVM quit or hang (like a deadlock). Otherwise - no.Java 语言规范保证 finally 在 try 语句完成之前被调用。
try 语句可能会由于常见原因而无法完成,Borealid 的回答中已列举了这些原因。
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.
如果控制权来自于 try 或 catch 块,那么finally 块肯定会被执行。如果您知道如何设法阻止控件脱离这些块:
通过编写退出语句,或
无限循环等。
那么finally块将不会被执行。
一般来说,我们编写finally块是为了“清理”的目的。
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.