2

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 ?

Community
  • 1
  • 1
Benj
  • 1,184
  • 7
  • 26
  • 57

3 Answers3

5

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();
Community
  • 1
  • 1
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
0

You can use Thread.setDefaultUncaughtExceptionHandler(Thread.UncaughtExceptionHandler eh) for that case if i got it right.

See Thread.setDefaultUncaughtExceptionHandler

Clayn
  • 1,016
  • 9
  • 11
0

There is a method setDefaultUncaughtExceptionHandler in Thread

user140547
  • 7,750
  • 3
  • 28
  • 80