未捕获异常去哪里了?
一个异常被抛出后,如果没有被捕获处理,那么会一直向上抛出,直到被main()/Thread.run()抛出。异常被main()/Thread.run() 抛出后,会由虚拟机调用Thread 的 dispatchUncaughtException方法:
/**
* 向 handler 分派未捕获的异常。 该方法仅由JVM调用。
*/
private void dispatchUncaughtException(Throwable e) {
getUncaughtExceptionHandler().uncaughtException(this, e);
}
// 获取未捕获异常处理的 handler,如果没有设置则返回当前线程所属的ThreadGroup
public UncaughtExceptionHandler getUncaughtExceptionHandler() {
return uncaughtExceptionHandler != null ?
uncaughtExceptionHandler : group;
}
ThreadGroup继承自 UncaughtExceptionHandler,实现了默认的处理方法:
public void uncaughtException(Thread t, Throwable e) {
if (parent != null) { // 父级优先处理
parent.uncaughtException(t, e);
} else {
Thread.UncaughtExceptionHandler ueh =
Thread.getDefaultUncaughtExceptionHandler();
if (ueh != null) {
ueh.uncaughtException(t, e);
} else if (!(e instanceof ThreadDeath)) { // 没有配置handler时的处理方式
System.err.print("Exception in thread \""
+ t.getName() + "\" ");
e.printStackTrace(System.err);
}
}
}
当有异常被main()/Thread.run() 抛出后,JVM会调用 dispatchUncaughtException 来寻找handler进行处理。而如果没有自定义hanlder进行处理,则会调用 System.err 进行输出。
线程对异常的处理
本文将线程实现分为两种,无返回值的Runnable实现 和 有返回值的FutureTask实现。然后分为 Thread 、ThreadPoolExecutor 和 ScheduledThreadPoolExecutor 三种情况来讨论异常的处理。
一、Thread 异常处理
Thread 线程的有很多种实现形式,基于 Runnable 的没有返回值的线程,无法在主线程感知到异常,没有捕获的异常只会输出到控制台,如果没有捕获异常,进行处理或日志记录,会造成异常丢失。有返回值的 FutureTask ,未捕获的异常,会在获取返回值时传递给主线程。
- 主线程无法捕获子线程异常
public static void catchInMainThread(){
try {
Thread thread = new Thread(() -> {
System.out.println( 1 / 0);
});
thread.start();
} catch (Exception e1) {
System.out.println("catched exception in main thread");
}
}
// 代码一输出
Exception in thread "Thread-0" java.lang.ArithmeticException: / by zero
at ThreadExecptionTest.lambda$0(ThreadExecptionTest.java:14)
at java.lang.Thread.run(Thread.java:745)
上述代码无法捕获到异常,根据开篇介绍的默认处理机制,异常在子线程的Thread.run()方法中抛出后,JVM会调用 dispatchUncaughtException 方法最终输出到控制台。
2. 子线程处理Runnable异常
public static void catchInRunThread() {
Thread thread = new Thread(() -> {
try {
System.out.println(1 / 0);
} catch (Exception e1) {
// 异常处理,日志记录等
System.out.println("catched exception in child thread");
}
});
thread.start();
}
// 代码二输出结果
catched exception in child thread
代码二展示了线程内按需处理异常的方式,这是一种推荐的线程内异常处理方法。
3. 主线程处理FutureTask异常
public static void catchInFuture() {
FutureTask<Integer> futureTask = new FutureTask<>(() -> {
return 1/0;
});
Thread thread = new Thread(futureTask);
thread.start();
try {
futureTask.get();
} catch (InterruptedException | ExecutionException e) {
System.out.println("catched exception in main thread by future");
// e.printStackTrace();
}
}
输出如下:
catched exception in main thread by future
FutureTask 的异常成功在主线程里处理。
对应的源码:
/**
* Causes this future to report an {@link ExecutionException}
* with the given throwable as its cause, unless this future has
* already been set or has been cancelled.
*
* <p>This method is invoked internally by the {@link #run} method
* upon failure of the computation.
*
* @param t the cause of failure
*/
protected void setException(Throwable t) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = t;
UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
finishCompletion();
}
}
4. 配置默认线程异常处理方式
public static void catchByExceptionHandler() {
Thread thread = new Thread(() -> {
System.out.println(1 / 0);
});
UncaughtExceptionHandler eh = new MyUncaughtExceptionHandler();
thread.setUncaughtExceptionHandler(eh);
thread.start();
}
static class MyUncaughtExceptionHandler implements UncaughtExceptionHandler{
@Override
public void uncaughtException(Thread t, Throwable e) {
// 异常处理,日志记录等
System.out.println("catched exception in ExceptionHandler");
}
}
// 代码三输出:
catched exception in ExceptionHandler
使用UncaughtExceptionHandler 来处理未捕获异常也是一个可参考的方案。
二、ThreadPoolExecutor 异常处理
public class ThreadPoolExecutorExceptionTest {
public static void main(String[] args) throws InterruptedException, IOException {
ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
executeThreadPoolExecutor(executor);
Thread.sleep(100);
submitThreadPoolExecutorWithOutGet(executor);
Thread.sleep(100);
submitThreadPoolExecutorAndGet(executor);
Thread.sleep(100);
executor.shutdown();
}
// Runnable子线程没有捕获异常
static void executeThreadPoolExecutor(ThreadPoolExecutor executor) {
System.out.println("\n*****executeThreadPoolExecutor*****");
executor.execute(() -> {
System.out.println(1 / 0);
});
}
// Callable不获取返回值
static void submitThreadPoolExecutorWithOutGet(ThreadPoolExecutor executor) {
System.out.println("\n*****submitThreadPoolExecutorWithOutGet*****");
executor.submit(() -> {
System.out.println(1 / 0);
});
}
// Callable获取返回值
static void submitThreadPoolExecutorAndGet(ThreadPoolExecutor executor) {
System.out.println("\n*****submitThreadPoolExecutorAndGet*****");
Future<?> future = executor.submit(() -> {
System.out.println(1 / 0);
});
try {
future.get();
} catch (InterruptedException | ExecutionException e) {
System.out.println("catched exception in main thread by future");
// e.printStackTrace();
}
}
}
上面展示了三种ThreadPoolExecutor提交任务的形式,输出如下:
*****executeThreadPoolExecutor*****
Exception in thread "pool-1-thread-1" java.lang.ArithmeticException: / by zero
at test.ThreadTest.lambda$1(ThreadTest.java:65)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
*****submitThreadPoolExecutorWithOutGet*****
*****submitThreadPoolExecutorAndGet*****
catched exception in main thread by future
直接用execute执行Runnable方法,如果主线程里的异常未捕获,将被默认handler输出到控制台,与Thread执行任务类似。如果使用submit执行FutureTask任务,而不调用get方法获取返回值,则会造成异常丢失现象。使用FutureTask只有调用get方法才能感知到子线程是否正常执行。因此,为了确保任务顺利执行,需使用get方法确认返回结果是否有异常抛出。
三、ScheduledThreadPoolExecutor 异常处理
之所以要将ScheduledThreadPoolExecutor 线程池单独拿出来讲,是因为ScheduledThreadPoolExecutor 的调度方法与普通线程池执行方法不同,有着特殊的规则。
ScheduledThreadPoolExecutor 有个三个调度方法:schedule、scheduleAtFixedRate、scheduleWithFixedDelay,schedule方法有个重载方法,可以传Callable执行
谨防 ScheduledThreadPoolExecutor 异常丢失
从上图我们可以看到,这几个方法都有返回值为 ScheduledFuture ,根据前面的分析我们知道有返回值的Future可以在获取返回值是捕获到异常,不获取返回值就会造成异常丢失。我们来验证一下:
public class ScheduledPoolExecptionTest {
public static void main(String[] args) {
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
schedule(executor);
}
static void schedule(ScheduledThreadPoolExecutor executor) {
executor.schedule(() -> {
int n = 1/0; // 应该抛出异常
}, 10, TimeUnit.NANOSECONDS);
}
}
用ScheduledThreadPoolExecutor的schedule方法执行Runnable,上述代码没有任何输出,异常消失了。这是平时我们使用调度线程池很容易犯的一个错误,这种异常消失在生产环境中将产生难以发现的问题。
ScheduledThreadPoolExecutor 的其他几个调度方法也会产生类似的问题。由于我们执行的是Runnable任务,往往不会调用future的get方法,因此在开发中,应该多加小心这种异常吞并。避免产生此问题,尽量在线程内捕获异常并处理;
ScheduledThreadPoolExecutor 的execute方法和submit继承自
ThreadPoolExecutor,异常处理机制一样。
总结
不管是Thread 、ThreadPoolExecutor 还是ScheduledThreadPoolExecutor,都应秉承线程内部处理的原则,做到自己的事情自己办。正确的处理、记录异常,及时的发现问题,避免不必要的麻烦。
网友评论