在try\finally块中是否有这样的情况,finally不会被执行?

发布于 2024-09-14 16:54:55 字数 186 浏览 4 评论 0原文

我正在学习面向对象编程的测试,我想知道是否存在考虑以下代码的情况:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

记忆之渊 2024-09-21 16:54:55

是的。如果您使 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.

几度春秋 2024-09-21 16:54:55

如果您在try中调用System.exit(0)。或者做一些让 JVM 退出或挂起的事情(比如死锁)。否则 - 不。

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

大姐,你呐 2024-09-21 16:54:55

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.

灯下孤影 2024-09-21 16:54:55

如果控制权来自于 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文