此答案基於Esko Luontola,但它提供了一個工作示例。
與Runnable接口的run()方法不同,Callable的call()方法允許拋出一些異常。下面是一個實現的例子:
public class MyTask implements Callable<Integer> {
private int numerator;
private int denominator;
public MyTask(int n, int d) {
this.numerator = n;
this.denominator = d;
}
@Override
// The call method may throw an exception
public Integer call() throws Exception {
Thread.sleep(1000);
if (denominator == 0) {
throw new Exception("cannot devide by zero");
} else {
return numerator/denominator;
}
}
}
執行人提供了一種機制,以一個線程中運行一個可調用和處理任何類型的異常:
public class Main {
public static void main(String[] args) {
// Build a task and an executor
MyTask task = new MyTask(2, 0);
ExecutorService threadExecutor = Executors.newSingleThreadExecutor();
try {
// Start task on another thread
Future<Integer> futureResult = threadExecutor.submit(task);
// While task is running you can do asynchronous operations
System.out.println("Something that doesn't need the tasks result");
// Now wait until the result is available
int result = futureResult.get();
System.out.println("The result is " + result);
} catch (ExecutionException e) {
// Handle the exception thrown by the child thread
if (e.getMessage().contains("cannot devide by zero"))
System.out.println("error in child thread caused by zero division");
} catch (InterruptedException e) {
// This exception is thrown if the child thread is interrupted.
e.printStackTrace();
}
}
}
看一看以下的答案: [如何捕捉從一個線程的異常] [1] [1]:http://stackoverflow.com/questions/ 6546193 /如何抓住線程中的異常 – 2013-01-01 06:14:54