setUncaughtExceptionHandler 用于获取线程运行时异常
线程在执行时是不能抛出 checked 异常的,IDE 只会提示你用 try-catch 包裹起来。因此主线程无法直接获取子线程的线程信息,而每个 Thread 可以通过 setUncaughtExceptionHandler 注册一个回调接口
setUncaughtExceptionHandler
public class ThreadUncaughtException {
public static void main(String[] args) {
Thread t1 = new Thread("t1"){
@Override
public void run() {
throw new RuntimeException("wrong");
}
};
t1.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println(t.getName() + "; error=" + e.getMessage());
}
});
t1.start();
}
}
输出结果
t1; error=wrong
Process finished with exit code 0