如何避免finally块不执行的场景 [英] How to avoid a scenario in which finally block does not execute

查看:195
本文介绍了如何避免finally块不执行的场景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在接受采访时被问到,当最后一块没有执行时。我回答说,当JVM在调用finally或调用System.exit()之前突然关闭时。然后我被问到如何避免这种情况,以便我们的程序始终保持执行状态。应该处理这种情况。我们能处理这样的情况吗?如果有,怎么样?
提前致谢。

I was asked in an interview that when finally block does not execute. I replied that when JVM shuts down abruptly before the finally is called or when System.exit() is called. Then I was asked how can we avoid that scenario so that our program always remain executing. That is such a scenario should be handled. Can we handle such a scenario. If yes how? Thanks in advance.

推荐答案

即使最终失败但仍会执行shutdownhook。

Even finally fails but still shutdownhook will be executed.

答案是 -

Runtime#addShutdownHook




Java虚拟机关闭以响应两种
事件:

The Java virtual machine shuts down in response to two kinds of events:


  • 当最后一个非守护程序线程退出或调用退出(等效,System.exit)方法时,程序正常退出,或者

  • 虚拟机终止以响应用户中断,例如键入^ C或系统范围的事件,例如用户注销或

    系统关闭。

Java docs

代码 -

Runtime.addShutdownHook(new Thread {
  public void run() {
    System.out.println("Just before going down..");
  });

这篇关于如何避免finally块不执行的场景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆