【多线程】java线程的未捕获异常,JVM处理机制

当线程出现未捕获异常(即抛出一个异常)

  1. JVM将调用Thread.dispatchUncaughtException();
/**
 * 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);
}

2.getUncaughtExceptionHandler(),判断自己独属于CurrentThread的uncaughtExceptionHandler是否为null,不为null则返回返回UncaughtExceptionHandler,为null 则返回group (extends UncaughtExceptionHandler)

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

3.调用 uncaughtException()

如果返回是ThreadGroup的话,默认会一直找到顶层ThreadGroup(假如中间的ThreadGroup不修改),然后会找 Thread类共用的 defaultUncaughtExceptionHandler ,如果存在则调用,如果不存在,则 打印线程名字和异常

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);
            }
        }
    }

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容