了解一下ThreadGroup的uncaughtException方法

2022-08-02,

为什么会想要了解ThreadGroup的uncaughtException方法

起源于Thread类中的UncaughtExceptionHandler接口,详情如下:

可以发现UncaughtExceptionHandler是个函数式接口。

那么找找UncaughtExceptionHandler接口和Thread类到底有什么关系?会看到如下方法

当线程在运行过程中出现异常时, 就会回调UncaughtExceptionHandler接口,然后就可以知道是哪个线程出了错,该方法就是获取相关UncaughtExceptionHandler接口的方法。同时截图中代码的逻辑表示,如果该线程的UncaughtExceptionHandler为null,那么就会去获取该线程所在线程组的UncaughtExceptionHandler接口。

那为什么该方法明明要返回UncaughtExceptionHandler接口类,却可以返回group,原因如下

可以发现group对象是ThreadGroup类的实例,同时是UncaughtExceptionHandler接口的子类,所以能够返回group。

那么作为UncaughtExceptionHandler接口的子类,必然要实现UncaughtExceptionHandler接口中的抽象方法,所以接着看看uncaughtException方法在ThreadGroup类的实现

ThreadGroup的uncaughtException方法源码如下:

private final ThreadGroup parent;

public class ThreadDeath extends Error {
    private static final long serialVersionUID = -4417128565033088268L;
}
public void uncaughtException(Thread t, Throwable e) {
    //如果父级线程组不为null,那么就使用父级线程组的uncaughtException
    if (parent != null) {
        parent.uncaughtException(t, e);
    } else {
        //否则获取全局默认的UncaughtExceptionHandler 
        Thread.UncaughtExceptionHandler ueh =
            Thread.getDefaultUncaughtExceptionHandler();
        if (ueh != null) {
            //不为null,则使用全局默认的UncaughtExceptionHandler的uncaughtException方法
            ueh.uncaughtException(t, e);
        } else if (!(e instanceof ThreadDeath)) {
            //如果以上两者都不满足,则将异常的堆栈信息定向到System.err
            System.err.print("Exception in thread \""
                             + t.getName() + "\" ");
            e.printStackTrace(System.err);
        }
    }
}

本文地址:https://blog.csdn.net/weixin_38106322/article/details/107397095

《了解一下ThreadGroup的uncaughtException方法.doc》

下载本文的Word格式文档,以方便收藏与打印。