java Callable 中的异常处理是如何完成的
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12305667/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How is exception handling done in a Callable
提问by user1649415
I understand that callable's call can throw the exception to the parent method calling it which is not the case with runnable.
我知道 callable 的调用可以向调用它的父方法抛出异常,而 runnable 则不是这种情况。
I wonder how because it's a thread method and is the bottommost method of the thread stack.
我想知道如何,因为它是一个线程方法,并且是线程堆栈的最底层方法。
回答by Denys Séguret
The point of Callable
is to have your exception thrown to your calling thread, for example when you get the result of a Future
to which you submitted your callable
.
点Callable
是让你抛出异常到你调用线程,例如,当你得到的结果Future
您提交到callable
。
public class CallableClass implements Callable<String> {
...
}
ExecutorService executor = new ScheduledThreadPoolExecutor(5);
Future<Integer> future = executor.submit(callable);
try {
System.out.println(future.get());
} catch (Exception e) {
// do something
}
回答by main--
Callable.call()
can'tbe the bottommost stack frame. It's always called by another method that will then catch the exception. Callable
should usually be used to asynchronously compute values and later get them with a Future
object. The operation mightthrow an exception that is later rethrown when you try to get the Future
's value.
Callable.call()
不能是最底层的堆栈框架。它总是由另一个方法调用,然后将捕获异常。Callable
通常应该用于异步计算值,然后用Future
对象获取它们。该操作可能会抛出异常,稍后在您尝试获取Future
的值时会重新抛出该异常。
Runnable
is simply supposed to run an operation that doesn't return anything. All exception handling should be done within the Runnable
because it's unclear how any exceptions thrown in Runnable.run()
should be handled. (The exception from a Callable
is usually returned to the caller with the Future
)
Runnable
只是应该运行一个不返回任何内容的操作。所有异常处理都应该在 内完成,Runnable
因为不清楚Runnable.run()
应该如何处理抛出的任何异常。(来自 a 的异常Callable
通常用 返回给调用者Future
)