Using UncaughtExceptionHandler effectively

后端 未结 2 830
Happy的楠姐
Happy的楠姐 2020-12-30 18:21

I got to know about this Java 1.5 capability recently and I developed a sample code to use this. My objective is to restart the thread when it gets dead due to an uncaught e

相关标签:
2条回答
  • 2020-12-30 18:37

    The approach I suggest is to not let exceptions leak out of your threads. The uncaught exception handler is a nifty tool, however, I suggest you have a design or code issue if you are using it to make sure your thread is running. Your thread is dying a horrible death and simply ignoring that and restarting a new one in its place is probably not what you want to do, even if you were able to figure out the sleeping thread issue.

    Imagine instead of in your thread, the problem is with your main() method - would you let the same exception leak all the way out and kill your app? If not, what would you do to mitigate the issue? You wouldn't write an exception handler that calls main() again right? Whatever you would do, that is what you should do in your thread.

    0 讨论(0)
  • 2020-12-30 18:51

    You should not restart the thread that is about to exit. The method is invoked when the given thread terminates. So you can only create and start a new thread. If you know about the threads class (by instanceof...) you can obtain the runnable from it and create a new thread in the terminating threads group and start it from the UncaughtExceptionHandler.

    But aware: I would check for specific exceptions. A minimum can be: restart only if the throwable is a runtime exception, not an error!

    0 讨论(0)
提交回复
热议问题