java · 2025-05-31 0

Future 的 ExecutionException 和 InterruptedException 异常

@Test
public void test1() {
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Future<?> future = executor.submit(() -> {
        throw new IllegalArgumentException("Student say error");
    });

    try {
        /**
         * future 线程内抛出的异常,会被 ExecutionException 包装,这里需要解原异常
         * @see FutureTask#report(int s)
         */
        future.get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        // 获取原始异常
        Throwable originalException = e.getCause();
        e.printStackTrace();
    }
}