为我的应用程序的所有线程定义一个全局UncaughtExceptionHandler

问题描述:

我想在我的Java应用程序中定义一个应用程序级别 UncaughtExceptionHandler ,如果在我的应用程序的一个线程中抛出未捕获的异常,则会调用该应用程序级别。
我知道这是可能的定义一组线程的未捕获的异常( ThreadGroup ),我实际上正在使用它,但是我想为没有定义自己的未捕获的异常处理程序或没有关联的线程定义一个全局未捕获的异常到一组具有默认异常处理程序定义的线程。

I want to define one application level UncaughtExceptionHandler in my Java application that is called if an uncaught exception is thrown in one thread of my application. I know that is possible define an uncaught exception for a group of thread (ThreadGroup) and i'm actually using it, but i want to define a global uncaught exception for threads that don't have defined their own uncaught exception handler or that are not associated to a group of threads that have a default exception handler defined.

所以例如我想要这样做:

So for example i wanna reach something like this :

1° LEVEL ---> Call thread own UncaughtExceptionHandler ---> 2° LEVEL Call Thread Group UncaughtExceptionHandler ---> 3° LEVEL Call application(default) UncaughtExceptionHandler 

简单来说,我想覆盖默认的UncaughtExceptionHandler并定义我自己的处理程序,而不是在 System.err (这是默认行为)上打印堆栈跟踪。

In simple terms i want to override the default UncaughtExceptionHandler and define my own handler instead of print the stack trace on the System.err (that is the default behaviour).

例如在C#.NET中,我执行类似处理应用程序的Main()方法中的未处理的线程异常事件处理程序:

For example in C# .NET i do something similar handling the unhandled and thread exception event handler in the Main() method of the application :

AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); 
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);

甚至可以在Java中完成?

Can be done even in Java ?

如何覆盖Java中的默认UncaughtExceptionHandler?

Thread.setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler ex)

这应该可以实现你想要的。

This should achieve what you are looking for.

正如文档所述


设置线程由于未捕获异常突然终止而调用的默认处理程序,并且没有为该线程定义其他处理程序。

Set the default handler invoked when a thread abruptly terminates due to an uncaught exception, and no other handler has been defined for that thread.

还有一个有趣的注释(也在文档中)关于您在ThreadGroup中使用处理程序

And an interesting note (also in the docs) regarding you using the handler in the ThreadGroup


请注意,默认未捕获的异常处理程序通常不应该为
推迟到线程的ThreadGroup对象,因为这可能导致无限
递归。

Note that the default uncaught exception handler should not usually defer to the thread's ThreadGroup object, as that could cause infinite recursion.