编程语言
首页 > 编程语言> > 在java中的shutdown hook中抛出异常会发生什么

在java中的shutdown hook中抛出异常会发生什么

作者:互联网

如果在java中执行关闭挂钩期间抛出未捕获的异常,jvm是否立即退出而不运行其余已注册的关闭挂钩(如果有)?来自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.

似乎其他关机钩子应该运行…

作为一个后续问题,拥有一段可能在关闭钩子中引发异常的代码可能不是一个好主意?如果你无法避免它,尝试捕获关闭钩子内的异常是一个好习惯吗?

解决方法:

由于addShutdownHook方法采用Thread,因此每个单独的shutdown钩子都是自己的Thread.未捕获异常的默认行为是打印错误消息并终止线程.由于钩子具有相同的行为,因此以错误结尾的单个关闭钩子不应阻止其他钩子运行.

请注意,我实际上没有测试过这个……

标签:java,exception-handling,jvm,shutdown-hook
来源: https://codeday.me/bug/20190517/1123676.html