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

时间:2016-04-17 22:05:02

标签: java exception executorservice callable

捕获异常的一般建议是,最好是具体的,而不是仅仅从最广泛的类中捕获异常: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之外我似乎无法捕获任何内容。

如果调用方法抛出了多个不同的异常,那么有人会如何分别捕获不同的异常?

1 个答案:

答案 0 :(得分:4)

您将始终获得ExecutionException。根异常将被设置为原因。在getCause()实例上调用ExecutionException以获取Callable中抛出的实际异常。