Java-UncaughtExceptionHandler 捕获线程异常

实现 UncaughtExceptionHandler 类,重写 uncaughtException 方法。

public class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
    @Override
    public void uncaughtException(Thread t, Throwable e) {
        System.out.println(Thread.currentThread().getName() + "异常");
        e.printStackTrace();
    }
}

创建线程,并设置异常捕获

public static void main(String[] args) {
    Thread thread = new Thread(() -> {
        int b = 5 / 0;
    });
    
    // 设置所有线程
    // Thread.setDefaultUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
    
    // 捕获指定线程中的异常
    thread.setUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
    thread.start();
}

原文地址:https://www.cnblogs.com/jhxxb/p/10879983.html