Reputation: 223
The general advice for catching exceptions is that it's better to be specific, instead of just catching exceptions from the broadest class: java.lang.Exception.
But it seems like the only exception from callable is 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();
}
}
In the above code, I would like to catch NumberFormatException, but I can't seem to catch anything except ExecutionException.
If there are multiple different exceptions thrown from the call method, how would someone catch the different exceptions separately?
Upvotes: 1
Views: 72
Reputation: 201088
You will always get an ExecutionException
. The root exception will be set as the cause. Call getCause()
on the ExecutionException
instance to get to the actual exception that was thrown in the Callable
.
Upvotes: 4