![](/img/trans.png)
[英]Java: ExecutorService and Callables, unable to catch exception
[英]Can't catch specific exception using ExecutorService and Callables?
捕獲異常的一般建議是,最好是具體一些,而不是僅捕獲最廣泛的類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之外,我似乎什么也不能捕獲。
如果call方法引發了多個不同的異常,那么有人將如何分別捕獲不同的異常?
您將始終獲得ExecutionException
。 根本異常將被設置為原因。 在ExecutionException
實例上調用getCause()
以獲取在Callable
中引發的實際異常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.