Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
324 views
in Technique[技术] by (71.8m points)

java - Defining one global UncaughtExceptionHandler for all threads of my application

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...