如果在 java 中执行关闭 Hook 期间抛出未捕获的异常,jvm 是否会立即退出而不运行其余已注册的关闭 Hook (如果有)?来自 javadocs:
Uncaught exceptions are handled in shutdown hooks just as in any other thread, by invoking the uncaughtException method of the thread's ThreadGroup object. The default implementation of this method prints the exception's stack trace to System.err and terminates the thread; it does not cause the virtual machine to exit or halt.
似乎其他关闭 Hook 应该运行...
作为后续问题,拥有一段可能会在关闭 Hook 中引发异常的代码可能不是一个好主意?如果无法避免, try catch 关闭 Hook 内的异常是否是一个好习惯?
最佳答案
自 addShutdownHook方法需要一个线程,每个单独的关闭 Hook 都是它自己的线程。未捕获异常的默认行为是打印错误消息并终止线程。由于 Hook 具有相同的行为,因此以错误结尾的单个关闭 Hook 不应阻止其他 Hook 运行。
请注意,我还没有真正测试过这个......
关于java - 当在 java 中的关闭钩子(Hook)内抛出异常时会发生什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13770480/