统一处理子线程异常

方法一(不推荐):在子线程中捕捉。

public class CantCatchDirectly implements Runnable {

    public static void main(String[] args) throws InterruptedException {
        new Thread(new CantCatchDirectly(), "MyThread-1").start();
        Thread.sleep(100);
        new Thread(new CantCatchDirectly(), "MyThread-2").start();
        Thread.sleep(100);
        new Thread(new CantCatchDirectly(), "MyThread-3").start();
        Thread.sleep(100);
        new Thread(new CantCatchDirectly(), "MyThread-4").start();
    }


    @Override
    public void run() {
        try {
            throw new RuntimeException();
        } catch (Exception e) {
            System.out.println("捕捉异常");
        }
    }
}

方法二(推荐):使用 UncaughtExceptionHandler

UncaughtExceptionHandler 配置

uncaughtException 方法里是捕获到异常后处理方法,这里打印出来只是示例。实际上可以发邮件,电话告警,包装成统一的异常类型,做法很多。

public class MyUncaughtExceptionHanlder implements Thread.UncaughtExceptionHandler {
    private String name;

    public MyUncaughtExceptionHanlder(String name) {
        this.name = name;
    }

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        System.out.println(t.getName() + "线程异常终止了");
        System.out.println(name + "捕获了异常" + e);
    }
}

使用方式有三种

  • 给程序统一设置。
  • 给线程池设置。
  • 给每个线程单独设置(不推荐)。
使用 MyUncaughtExceptionHanlder,程序统一设置。
public class UseOwnUncaughtExceptionHandler implements Runnable {
    public static void main(String[] args) throws InterruptedException {
        Thread.setDefaultUncaughtExceptionHandler(new MyUncaughtExceptionHanlder("捕获器1"));

        new Thread(new UseOwnUncaughtExceptionHandler(), "MyThread-1").start();
        Thread.sleep(100);
        new Thread(new UseOwnUncaughtExceptionHandler(), "MyThread-2").start();
        Thread.sleep(100);
        new Thread(new UseOwnUncaughtExceptionHandler(), "MyThread-3").start();
        Thread.sleep(100);
        new Thread(new UseOwnUncaughtExceptionHandler(), "MyThread-4").start();
    }

    @Override
    public void run() {
        throw new RuntimeException();
    }
}

你可能感兴趣的:(统一处理子线程异常)