gpt4 book ai didi

java - 如何避免finally block 不执行的场景

转载 作者:行者123 更新时间:2023-11-30 09:00:29 24 4
gpt4 key购买 nike

我在采访中被问到什么时候 finally block 不执行。我回答说,当 JVM 在调用 finally 之前或在调用 System.exit() 之前突然关闭时。然后有人问我如何才能避免这种情况,以便我们的程序始终保持执行状态。那就是应该处理这样的场景。我们能处理这样的场景吗?如果是如何?提前致谢。

最佳答案

即使 finally 失败,shutdownhook 也会被执行。

答案是——

Runtime#addShutdownHook

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

  • The program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit) method is invoked, or
  • The virtual machine is terminated in response to a user interrupt, such as typing ^C, or a system-wide event, such as user logoff or
    system shutdown.

Java docs

代码-

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

关于java - 如何避免finally block 不执行的场景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26773272/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com