首先看一个例子
int a=10/0;
控制台输出:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at threadpool.ThreadPoolTest.main(ThreadPoolTest.java:56)
public static void main(String[] args) {
Thread.currentThread().setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("["+t.getName()+"\t" +e.getMessage()+"]");
System.out.println("被除数不能为零");
}
});
int a=10/0;
}
输出结果
[main / by zero]
被除数不能为零
为什么这样会改变输出结果呢?因为在不做异常捕获时JVM会自动捕获异常
/**
* Dispatch an uncaught exception to the handler. This method is
* intended to be called only by the JVM.
* 将未捕获的异常分派给处理程序。此方法旨在仅由 JVM 调用
*/
private void dispatchUncaughtException(Throwable e) {
getUncaughtExceptionHandler().uncaughtException(this, e);
}
getUncaughtExceptionHandler()方法先会去判断uncaughtExceptionHandler 是否为null ,如果是的就会用ThreadGroup group 这个对象
public UncaughtExceptionHandler getUncaughtExceptionHandler() {
return uncaughtExceptionHandler != null ?
uncaughtExceptionHandler : group;
}
ThreadGroup uncaughtException()方法
public void uncaughtException(Thread t, Throwable e) {
if (parent != null) {
parent.uncaughtException(t, e);
} else {
//看一当前线程下是否设置了默认的UncaughtExceptionHandler
Thread.UncaughtExceptionHandler ueh =
Thread.getDefaultUncaughtExceptionHandler();
if (ueh != null) {
//如果有就用设置的UncaughtExceptionHandler
ueh.uncaughtException(t, e);
} else if (!(e instanceof ThreadDeath)) {
//没有就用这个
System.err.print("Exception in thread \""
+ t.getName() + "\" ");
e.printStackTrace(System.err);
}
}
}
在上面的代码中,在当前线程中设置了UncaughtExceptionHandler(函数式接口),所以会用设置异常处理器。
除了上述方式还可以用下面这种方式来设置
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println(111);
}
});
如果两种都设置了就会用第一种方式,因为getUncaughtExceptionHandler()会优先使用第一种方式。
标签:10,Thread,int,void,System,UncaughtExceptionHandler,uncaughtException,main From: https://www.cnblogs.com/lyuSky/p/16845297.html