【发布时间】:2012-07-06 13:08:43
【问题描述】:
我想在 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() 函数引发了一些异常,我如何在 Outer 类中捕获它们?
【问题讨论】:
-
我会在匿名类中抓住它。这样就没有异常可以捕获。
-
另外,不要显式捕获每个检查的异常,因为您可能不会编写任何特定的处理代码。写
catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } -
是的 早些时候我也想过同样的事情,我会这样做,但是我想在异常处理代码中使用很多外部类的变量。而且我无法在 Inner 类中访问这些变量。
标签: java java.util.concurrent concurrent-programming