Defining one global UncaughtExceptionHandler for a

2020-02-09 03:45发布

问题:

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 

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).

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);

Can be done even in Java ?

How can i override the default UncaughtExceptionHandler in Java ?

回答1:

Thread.setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler ex)

This should achieve what you are looking for.

As the doc says

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.

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

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



回答2:

You need to set the default uncaught exception handler. This is a static method on the Thread class called setDefaultUncaughtExceptionHandler. Doing this will do set the exception handler for the application running. It will be the default for any new threads unless otherwise specified.