捕获线程的执行异常 在线程的run方法中,如果有受检异常必须进行捕获处理,如果想要 获 得 run() 方 法 中 出 现 的 运 行 时 异 常 信 息 , 可 以 通 过 回 调 UncaughtExceptionHandler 接口获得哪个线程出现了运行时异常.在 Thread 类中有关处理运行异常的方法有: getDefaultUncaughtExceptionHandler() 获 得 全 局 的 ( 默 认 的)UncaughtExceptionHandler getUncaughtExceptionHandler() 获 得 当 前 线 程 的 UncaughtExceptionHandler setDefaultUncaughtExceptionHandler(Thread.UncaughtExceptionHan dler eh) 设置全局的 UncaughtExceptionHandler setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler eh) 设置当前线程的 UncaughtExceptionHandler 当 线 程 运 行 过 程 中 出 现 异 常 ,JVM 会 调 用 Thread 类 的 dispatchUncaughtException(Throwable e) 方 法 , 该 方 法 会 调 用 getUncaughtExceptionHandler().uncaughtException(this, e); 如 果 想 要 获 得 线 程 中 出 现 异 常 的 信 息 , 就 需 要 设 置 线 程 的 UncaughtExceptionHandler
package com.example.demo.juc.day4;
/**
* @author zhangqi
* @date 2022/4/17 11:28
*/
public class Test3 {
public static void main(String[] args) {
// 设置全局的线程异常处理
Thread.setDefaultUncaughtExceptionHandler((thread, e) -> {
// 线程名
String name = thread.getName();
// 异常信息
String message = e.getMessage();
System.out.println("name = " + name + " message = " + message);
});
new Thread(() -> {
String n = null;
n.toString();
}, "t1").start();
new Thread(() -> {
System.out.println(10 / 0);
}, "t2").start();
Thread thread = new Thread(() -> {
System.out.println(10 / 0);
}, "t2");
thread.setUncaughtExceptionHandler((t, e) -> {
// 线程名
String name = thread.getName();
// 异常信息
String message = e.getMessage();
System.out.println("name ============================= " + name + " message ============================= " + message);
// =============================
});
thread.start();
}
/*
* 在实际开发中,这种设计异常处理的方式还是比较常用的,尤其是异常执行的方 法 如果线程产生了异常, JVM 会调用 dispatchUncaughtException()方法,在该方法 中调用了 getUncaughtExceptionHandler().uncaughtException(this, e); 如果当前线程设置了 UncaughtExceptionHandler 回调接口就直接调用它自己的 uncaughtException 方法, 如果没有 设置则调用当前线程所在线程组 UncaughtExceptionHandler 回调接口的 uncaughtException 方 法,如果线程组也没有设置回调接口,则直接把异常的栈信息定向到 System.err 中
*/
}