【问题标题】:Can't catch specific exception using ExecutorService and Callables?无法使用 ExecutorService 和 Callables 捕获特定异常?
【发布时间】:2016-08-09 12:40:07
【问题描述】:

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

但似乎可调用的唯一例外是 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,我似乎什么也捕捉不到。

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

【问题讨论】:

    标签: java exception executorservice callable


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-20
      • 2012-11-11
      • 2010-10-29
      • 1970-01-01
      相关资源
      最近更新 更多