本文介绍了System.exit()结果无法执行的finally块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究My application's under maintanace module

try {
    if (isUndermaintanace) {
        System.exit(1);
    } else {
        prepareResources();
    }           
} catch (Exception e) {
    printStack(e);
} finally {
    cleanResources();
}

当我传递isundermaintanace true时,最终没有执行.

When I am passing isundermaintanace true finally not executing.

我想念什么?还有其他方法吗?

What am I missing? Is there any other way to do that?

推荐答案

Finally. System.exit()是杀死程序的一种相当粗糙的方法,而最后是一个高级的OOP概念. System.exit()的运行速度非常快,清理工作越少越好.

Finally's don't execute if you kill the VM (or if the VM dies some other way). System.exit() is a rather crude method of killing the program, whereas finally is a high level OOP concept. System.exit() bails very quickly, doing as little cleanup as possible.

如果您进入任务管理器并杀死该进程或对该进程发出kill -9,您希望最终执行吗?含糊不清(非常含糊)是同一件事.

If you went into task manager and killed the process or issued a kill -9 on the process would you expect a finally to execute? It's vaguely (very vaguely) the same thing.

有几件事值得注意.特别是,我在帖子的第一部分撒了些谎.将System.exit()比喻为真正地立即杀死程序是一种误导.特别是,运行了关闭挂钩,并且如果已配置,则实际上可以运行终结器.但是请注意,该文档强烈建议不要使用runFinalizersOnExit.

There's a few things worth noting. In particular, I lied a bit in the first part of the post. It's misleading to liken System.exit() to truly instantly killing a program. In particular, shutdown hooks are ran, and if configured, finalizers can actually be ran. Note, however, that the docs fairly strongly suggest against using runFinalizersOnExit.

这篇关于System.exit()结果无法执行的finally块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 16:08