梳理UncaughtExceptionHandler源码20230220

Thread类

1、dispatchUncaughtException()方法应该是在native层触发,这个时候调用了getUncaughtExceptionPreHandler(),它的优先级比其他的UncaughtExceptionHandler要高

public final void dispatchUncaughtException(Throwable e) {
        1、UncaughtExceptionPreHandle优先级高
        Thread.UncaughtExceptionHandler initialUeh =
                Thread.getUncaughtExceptionPreHandler();
        if (initialUeh != null) {
            try {
                initialUeh.uncaughtException(this, e);
            } catch (RuntimeException | Error ignored) {
                // Throwables thrown by the initial handler are ignored
            }
        }
        2、调用UncaughtExceptionHandler
        getUncaughtExceptionHandler().uncaughtException(this, e);
    }

2、如果设置了uncaughtExceptionHandler,则用。否则用group(ThreadGroup类型)

public UncaughtExceptionHandler getUncaughtExceptionHandler() {
        return uncaughtExceptionHandler != null ?
            uncaughtExceptionHandler : group;
    }

ThreadGroup类

1、Thread类的构造方法,定义了ThreadGroup怎么取值

public Thread() {
        init(null, null, "Thread-" + nextThreadNum(), 0);
    }
ThreadGroup默认为空,取当前线程的ThreadGroup
private void init(ThreadGroup g, Runnable target, String name, long stackSize) {
        Thread parent = currentThread();
        if (g == null) {
            g = parent.getThreadGroup();
        }

        ...
        this.group = g;
        ...
    }

2、在ThreadGroup类的uncaughtException()方法,如果parent不为空,则直接调用它的uncaughtException(),否则,调用默认的handler

public void uncaughtException(Thread t, Throwable e) {
        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);
            }
        }
    }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容