所有线程的Java未捕获全局异常处理程序 [英] Java uncaught global exception handler for ALL threads

查看:343
本文介绍了所有线程的Java未捕获全局异常处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我问了一个关于如何覆盖默认Java异常处理的问题这里并被告知答案此处



现在的问题是:有没有办法将这个处理程序生成到所有线程,而不是在每个线程中明确声明?



我认为应该可以以某种方式获取所有线程,然后绑定异常处理程序?

解决方案

使用 Thread.setDefaultUncaughtExceptionHandler 。作为 javadoc 说:


通过设置默认未捕获的异常处理程序,应用程序可以更改未捕获的异常的方式被处理(例如登录到特定设备或文件)那些已经接受系统提供的任何默认行为的线程。


显然,如果一个线程已经有(非默认)处理程序,那么它不会受到默认行为的更改的影响。







我认为应该可以以某种方式获取所有线程,然后绑定异常处理程序?


这不是必需的,除非你想更改线程的非默认处理程序。如果您真的需要这样做,您可以通过遍历应用程序的 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:

"By setting the default uncaught exception handler, an application can change the way in which uncaught exceptions are handled (such as logging to a specific device, or file) for those threads that would already accept whatever "default" behavior the system provided."

Obviously, if a Thread already has a (non-default) handler, then it won't be affected by a change to the default behavior.


I think it should be possible to get all threads in some way, then bind them the exception handler ?

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未捕获全局异常处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆