Java uncaught global exception handler for ALL threads

前端 未结 3 1469
挽巷
挽巷 2021-01-17 06:16

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

相关标签:
3条回答
  • 2021-01-17 06:58

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

    See Thread.setDefaultUncaughtExceptionHandler

    0 讨论(0)
  • 2021-01-17 07:05

    There is a method setDefaultUncaughtExceptionHandler in Thread

    0 讨论(0)
  • 2021-01-17 07:19

    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();
    
    0 讨论(0)
提交回复
热议问题