此答案基于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