捕获其他线程的异常

  在A线程里起了另B线程,但B线程报错了,这时想要在A线程里捕获B线程的异常是无法做的,除非在捕获B线程前先设置线程捕获器。直接来看代码:

package com.wulinfeng.exceptionHandler;

import java.lang.Thread.UncaughtExceptionHandler;

public class ExceptionCatcher {

    public static void main(String[] args) {

        // 1、新线程抛异常,main线程无法捕获
        try {
            new Thread() {
                @Override
                public void run() {
                    System.out.println("第一个空指针来了:");
                    throw new NullPointerException();
                }
            }.start();
        } catch (Exception e) {
            System.out.println("第一次抛出异常!");
        }

        // 2、通过线程捕获异常
        try {

            // 先休眠,等上面的线程自动结束
            Thread.sleep(1000);

            // 先设置捕获线程
            Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {

                @Override
                public void uncaughtException(Thread t, Throwable e) {
                    System.out.printf("线程:%s 抛出异常:%s
", t.getName(), e.getClass().getName());
                    e.printStackTrace();
                }
            });

            // 新起线程抛出异常
            new Thread() {

                @Override
                public void run() {
                    System.out.println("第二个空指针来了:");
                    throw new NullPointerException();

                }
            }.start();

        } catch (

        Exception e) {
            System.out.println("第二次抛出异常!");
        }
    }
}

  运行结果:

第一个空指针来了:
Exception in thread "Thread-0" java.lang.NullPointerException
    at com.wulinfeng.exceptionHandler.ExceptionCatcher$1.run(ExceptionCatcher.java:16)
    at java.lang.Thread.run(Thread.java:745)
第二个空指针来了:
线程:Thread-1 抛出异常:java.lang.NullPointerException
java.lang.NullPointerException
    at com.wulinfeng.exceptionHandler.ExceptionCatcher$3.run(ExceptionCatcher.java:46)
    at java.lang.Thread.run(Thread.java:745)

  根据线程执行速度不同,新起的线程里exception和本地线程里字符串的打印顺序先后有可能不同。

原文地址:https://www.cnblogs.com/wuxun1997/p/6773165.html