我们在重写Thread的run()方法时,是被限制无法向上抛出异常的,而且java区分受检异常(checked exception)和非受检异常(unchecked exception),可能出现受检异常的代码,编译器会强制要求我们通过try/catch的方式进行异常处理。但是非受检异常不会被强制要求处理,如果我们想在线程里处理非受检异常,那么就需要使用Thread提供的UncaughtExceptionHandler。
使用方式如下:
package com.thread.demo.unit3;
/**
* @Author: Peacock__
* @Date: 2019/5/6 16:19
*/
public class ThreadExceptionDemo {
private static final int A = 10;
private static final int B = 0;
public static void main(String[] args) {
Thread t = new Thread(() -> {
try {
//休息5秒
Thread.sleep(5_000);
//制造ArithmeticException异常(非受检)
int result = A/B;
System.out.println(result);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
//设置UncaughtExceptionHandler
t.setUncaughtExceptionHandler(new MyExceptionHandler());
t.start();
}
static class MyExceptionHandler implements Thread.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
*/
@Override
public void uncaughtException(Thread t, Throwable e) {
//处理非受检异常
System.out.println("线程名称:"+t);
System.out.println("异常描述:"+e);
}
}
}
如果我们不设置UncaughtExceptionHandler,控制台执行到int result = A/B;时会在控制台打印异常信息。
设置UncaughtExceptionHandler后,控制台输出如下:
线程名称:Thread[Thread-0,5,main]
异常描述:java.lang.ArithmeticException: / by zero
Process finished with exit code 0