美文网首页
【多线程】java线程的未捕获异常,JVM处理机制

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

作者: 良辰夜 | 来源:发表于2018-05-08 00:15 被阅读0次

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

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

    相关文章

      网友评论

          本文标题:【多线程】java线程的未捕获异常,JVM处理机制

          本文链接:https://www.haomeiwen.com/subject/hzwbrftx.html