当前位置:   article > 正文

关于未捕获异常(Uncaught Exception)的处理

uncaught exception post /template/parser/ (192.168.2.138)

我们经常使用try..catch进行异常处理,但是对于Uncaught Exception是没办法捕获的。对于这类异常如何处理呢?

回顾一下thread的run方法,有个特别之处,它不会抛出任何检查型异常,但异常会导致线程终止运行。这非常糟糕,我们必须要“感知”到异常的发生。比如某个线程在处理重要的事务,当thread异常终止,我必须要收到异常的报告(email或者短信)。

在jdk 1.5之前貌似无法直接设置thread的Uncaught Exception Handler(具体未验证过),但从1.5开始可以对thread设置handler。

1. As the handler for a particular thread
当 uncaught exception 发生时, JVM寻找这个线程的异常处理器. 可以使用如下的方法为当前线程设置处理器

  1. public class MyRunnable implements Runnable {
  2. public void run() {
  3. // Other Code
  4. Thread.currentThread().setUncaughtExceptionHandler(myHandler);
  5. // Other Code
  6. }
  7. }


2. As the handler for a particular thread group
如果这个线程属于一个线程组,且线程级别并未指定异常处理器(像上节As the handler for a particular thread中那样),jvm则试图调用线程组的异常处理器。

线程组(ThreadGroup)实现了Thread.UncaughtExceptionHandler接口,所以我们只需要在ThreadGroup子类中重写实现即可

public class ThreadGroup implements Thread.UncaughtExceptionHandler

java.lang.ThreadGroup 类uncaughtException默认实现的逻辑如下:

  • 如果父线程组存在, 则调用它的uncaughtException方法.
  • 如果父线程组不存在, 但指定了默认处理器 (下节中的As the default handler for the application), 则调用默认的处理器
  • 如果默认处理器没有设置, 则写错误日志.但如果 exception是ThreadDeath实例的话, 忽略。

对应JDK的源码:

  1. public void uncaughtException(Thread t, Throwable e) {
  2. if (parent != null) {
  3. parent.uncaughtException(t, e);
  4. } else {
  5. Thread.UncaughtExceptionHandler ueh =
  6. Thread.getDefaultUncaughtExceptionHandler();
  7. if (ueh != null) {
  8. ueh.uncaughtException(t, e);
  9. } else if (!(e instanceof ThreadDeath)) {
  10. System.err.print("Exception in thread \""
  11. + t.getName() + "\" ");
  12. e.printStackTrace(System.err);
  13. }
  14. }
  15. }

3. As the default handler for the application (JVM)


Thread.setDefaultUncaughtExceptionHandler(myHandler);


不写了,打字太累,什么时候能有好用的语音输入editor.

转载于:https://my.oschina.net/shishaomeng/blog/121740

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/245377
推荐阅读
相关标签
  

闽ICP备14008679号