问题描述
我问了一个关于如何覆盖默认Java异常处理的问题。现在的问题是:有没有办法将这个处理程序生成到所有线程,而不是在每个线程中明确声明?
我认为应该可以以某种方式获取所有线程,然后绑定异常处理程序?
使用 Thread.setDefaultUncaughtExceptionHandler
。作为说:
显然,如果一个线程已经有(非默认)处理程序,那么它不会受到默认行为的更改的影响。
这不是必需的,除非你想更改线程的非默认处理程序。如果您真的需要这样做,您可以通过遍历应用程序的 ThreadGroup
层次结构来查找所有线程。 (除非你的应用程序是沙盒...)
编辑
正在运行的应用程序的线程列表可以使用找到:
设置< Thread> threadSet = Thread.getAllStackTraces()。keySet();
I asked a question about how to override the default Java Exception handling here and was told the answer here.
The question is now : is there a way to generify this handler to all threads without declaring explicitly in each thread ?
I think it should be possible to get all threads in some way, then bind them the exception handler ?
Use Thread.setDefaultUncaughtExceptionHandler
. As the javadoc says:
Obviously, if a Thread already has a (non-default) handler, then it won't be affected by a change to the default behavior.
That's not necessary ... unless you want to change a thread's non-default handler. If you really need to do that, you can find all threads by traversing the application's ThreadGroup
hierarchy. (Unless your app is sandboxed ...)
Edit
The thread list of the running app can be found using this answer :
Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
这篇关于所有线程的Java未捕获全局异常处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!