java的异常抛出机制

    /**
     * 在Thread类中定义了针对未被捕捉的异常的处理方式,其由JVM调用
     * Dispatch an uncaught exception to the handler. This method is
     * intended to be called only by the JVM.
     */
    private void dispatchUncaughtException(Throwable e) {
        getUncaughtExceptionHandler().uncaughtException(this, e);
    }
    
    /**
     * 获取对应的异常处理器,如果有手动设置指定,则获取对应的,否则获取该线程对应的线程组对象
     */
    public UncaughtExceptionHandler getUncaughtExceptionHandler() {
        return uncaughtExceptionHandler != null ?
            uncaughtExceptionHandler : group;
    }

 	/* The group of this thread */
    private ThreadGroup group;

  	// null unless explicitly set Thread中定义了未捕捉异常处理器,默认为null,除非通过setUncaughtExceptionHandler方法赋值
    private volatile UncaughtExceptionHandler uncaughtExceptionHandler;
    // null unless explicitly set  默认的异常处理器,也需要手动进行赋值
    private static volatile UncaughtExceptionHandler defaultUncaughtExceptionHandler;
/** ThreadGroup 实现了UncaughtExceptionHandler接口 */
public class ThreadGroup implements Thread.UncaughtExceptionHandler {...}

/** ThreadGroup 提供了默认实现 */
public void uncaughtException(Thread t, Throwable e) {
	  /*
	   * 先判断父线程组是否为null,不为null则调用父线程组的uncaughtException方法,
	   * 而父线程组如果都不重写该方法的话,最终会追溯到system线程组,它没有父线程组
	   */
      if (parent != null) {
          parent.uncaughtException(t, e);
      } else {
          Thread.UncaughtExceptionHandler ueh =
              Thread.getDefaultUncaughtExceptionHandler();
          // 尝试获取默认的异常处理器进行异常处理
          if (ueh != null) {
              ueh.uncaughtException(t, e);
          // 这里就是默认操作了,打印异常堆栈信息到控制台上
          } else if (!(e instanceof ThreadDeath)) {
              System.err.print("Exception in thread \""
                               + t.getName() + "\" ");
              e.printStackTrace(System.err);
          }
      }
  }

其实看ThreadGroup以及Thread的源码还是很好理清楚逻辑的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值