// 为某个特定线程指定 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 {
/**
* Method invoked when the given thread terminates due to the
* given uncaught exception.
* <p>Any exception thrown by this method will be ignored by the
* Java Virtual Machine.
* @param t the thread
* @param e the exception
*/
void uncaughtException(Thread t, Throwable e);
}
上述代码中,UncaughtExceptionHandler 是一个 FunctionalInterface,只有一个抽象方法,该回调接口被 Thread 中的 dispatchUncaughtException 方法调用。
/**
* Dispatch an uncaught exception to the handler. This method is
* intended to be called only by the JVM.
*/
private void dispatchUncaughtException(Throwable e) {
getUncaughtExceptionHandler().uncaughtException(this, e);
}
当线程在运行过程中出现异常时,JVM 会调用 dispatchUncaughtException 方法,该方法会将对应的线程实例以及异常信息传递给接口。
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();
}
}
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)
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/chengqiuming/article/details/123806621
内容来源于网络,如有侵权,请联系作者删除!