无法使用 ExecutorService 和 Callables 捕获特定异常?

Can't catch specific exception using ExecutorService and Callables?

捕获异常的一般建议是,最好具体一些,而不是仅仅从最广泛的范围中捕获异常class:java.lang.Exception。

但似乎 callable 的唯一异常是 ExecutionException。

package com.company;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class ThreadTest {

    private final static ArrayList<Callable<Boolean>> mCallables = new ArrayList<>();
    private final static ExecutorService mExecutor = Executors.newFixedThreadPool(4);

    public static void main(String[] args) throws Exception{
        testMethod();
    }

    static void testMethod() throws Exception {

        mCallables.clear();

        for(int i=0; i<4; i++){
            mCallables.add(new Callable<Boolean>() {

                @Override
                public Boolean call() throws Exception {
                    //if (Thread.currentThread().isInterrupted()) {
                    //    throw new InterruptedException("Interruption");
                    //}
                    System.out.println("New call");

                    double d = Double.parseDouble("a");

                    return true;
                } //end call method

            }); //end callable anonymous class
        }
        try {
            List<Future<Boolean>> f= mExecutor.invokeAll(mCallables);
            f.get(1).get();
            f.get(2).get();
            f.get(3).get();
            f.get(0).get();

        } catch (NumberFormatException e) {
            e.printStackTrace();
            System.out.println("Number Format exception");
        } catch (ExecutionException e) {
            String s = e.toString();
            System.out.println(s);
            System.out.println("Execution exception");
        } catch (Exception e) {
            System.out.println("Some other exception");
        }

        mExecutor.shutdown();
    }
}

在上面的代码中,我想捕获 NumberFormatException,但是除了 ExecutionException 似乎什么也捕获不到。

如果调用方法抛出多个不同的异常,如何分别捕获不同的异常?

你总会得到一个 ExecutionException。根异常将被设置为原因。在 ExecutionException 实例上调用 getCause() 以获取在 Callable.

中抛出的实际异常