Java uncaught global exception handler for ALL threads

前端 未结 3 1480
挽巷
挽巷 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 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 threadSet = Thread.getAllStackTraces().keySet();
    

提交回复
热议问题