我想在java中调用一个由于某种原因而阻塞的方法。我想要等待该方法X分钟,然后我想停止该方法。
我在StackOverflow上读到了一个解决方案,它给了我一个快速入门的机会。我在这里写下:
ExecutorService executor = Executors.newCachedThreadPool();
Callable<Object> task = new Callable<Object>() {
public Object call() {
return something.blockingMethod();
}
};
Future<Object> future = executor.submit(task);
try {
Object result = future.get(5, TimeUnit.SECONDS);
} catch (TimeoutException ex) {
// handle the timeout
} catch (InterruptedException e) {
// handle the interrupts
} catch (ExecutionException e) {
// handle other exceptions
} finally {
future.cancel(); // may or may not desire this
}但现在我的问题是,我的函数可能会抛出一些异常,我必须捕获这些异常并相应地执行一些任务。那么,如果在代码中,函数blockingMethod()出现一些异常,我如何在外部类中捕获它们呢?
发布于 2012-07-06 21:14:20
在您提供的代码中,您已经为此做好了一切准备。只需替换
// handle other exceptions使用您的异常处理。
如果您需要获取特定的Exception,可以通过以下方式获取:
Throwable t = e.getCause();为了区分你的异常,你可以这样做:
if (t instanceof MyException1) {
...
} else if (t instanceof MyException2) {
...
...发布于 2012-07-06 21:11:58
我想是在ExecutionException实例的cause中。
发布于 2012-07-06 21:14:27
在ExecutionException catch块中:e.getCause()
https://docs.oracle.com/javase/6/docs/api/java/lang/Throwable.html#getCause
https://stackoverflow.com/questions/11362823
复制相似问题