gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 02:58:31 27 4
gpt4 key购买 nike

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

但似乎 callable 的唯一异常(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,我似乎什么也捕获不到。

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

最佳答案

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

关于java - 无法使用 ExecutorService 和 Callables 捕获特定异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36682745/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com