// 为某个特定线程指定 UncaughtExceptionHandler public void setUncaughtExceptionHandler(UncaughtExceptionHandler eh) // 设置全局UncaughtExceptionHandler public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler eh) // 获取特定线程的 UncaughtExceptionHandler public UncaughtExceptionHandler getUncaughtExceptionHandler() // 获取全局的 UncaughtExceptionHandler public static UncaughtExceptionHandler getDefaultUncaughtExceptionHandler()二 点睛
线程在执行单元中不允许抛出 checked 异常,线程运行在自己的上下文中,派生它的线程将无法直接获得它允许中出现的异常信息。Java 为我们提供了 UncaughtExceptionHandler 接口,从而得知是哪个线程在运行时出错,以及出现了什么样的错误。
@FunctionalInterface
public interface UncaughtExceptionHandler {
void uncaughtException(Thread t, Throwable e);
}
上述代码中,UncaughtExceptionHandler 是一个 FunctionalInterface,只有一个抽象方法,该回调接口被 Thread 中的 dispatchUncaughtException 方法调用。
private void dispatchUncaughtException(Throwable e) {
getUncaughtExceptionHandler().uncaughtException(this, e);
}
当线程在运行过程中出现异常时,JVM 会调用 dispatchUncaughtException 方法,该方法会将对应的线程实例以及异常信息传递给接口。
三 实战 1 代码package concurrent;
import java.util.concurrent.TimeUnit;
public class UncatchExceptionHandlerDemo {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(1 / 0);
});
thread.setUncaughtExceptionHandler((t, e) -> {
System.out.println(t.getName() + " occur exception");
e.printStackTrace();
});
thread.start();
}
}
2 测试
Thread-0 occur exception
java.lang.ArithmeticException: / by zero
at concurrent.UncatchExceptionHandlerDemo.lambda$main$0(UncatchExceptionHandlerDemo.java:14)
at java.lang.Thread.run(Thread.java:748)



