通常情况下线程池中的异常会被吞掉不会被捕获
想要拿到线程池中的异常方式有两种
1、使用tyr catch块在当前线程捕获异常
ExecutorService executorService = Executors.newFixedThreadPool(1);
executorService.submit(() -> {
try {
int i = 1 / 0;
}catch (Exception e){
e.printStackTrace();
}
});
2、使用带返回值的 Callable接口通过返回Future对象,使用future.get()来接收线程池中的异常(Runnable不能返回future对象无法接收线程池中的异常)
ExecutorService executorService = Executors.newFixedThreadPool(1);
Future<String> future = executorService.submit(() -> {
int i = 1 / 0;
return "返回";
});
future.get();