为什么我收到一条错误消息,说没有抛出任何异常?
我在一个实现 Callable 的类中有这个:
public class MasterCrawler implements Callable {
public Object call() throws SQLException {
resumeCrawling();
return true;
}
//more code with methods that throws an SQLException
}
在执行这个 Callable 的其他类中,类似这样:
MasterCrawler crawler = new MasterCrawler();
try{
executorService.submit(crawler); //crawler is the class that implements Callable
}(catch SQLException){
//do something here
}
但我收到一个错误,并且 IDE 收到一条消息,提示 SQLException 永远不会抛出。这是因为我正在 ExecutorService 中执行?
更新:因此提交不会抛出 SQLException。我该如何执行 Callable (作为线程运行)并捕获异常?
已解决:
public class MasterCrawler implements Callable {
@Override
public Object call() throws Exception {
try {
resumeCrawling();
return true;
} catch (SQLException sqle) {
return sqle;
}
}
}
Future resC = es.submit(masterCrawler);
if (resC.get(5, TimeUnit.SECONDS) instanceof SQLException) {
//do something here
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当您调用
submit
时,您正在传递一个对象。您没有调用call()
。编辑
提交
返回未来 f.当您调用f.get()
时,该方法可能会抛出 ExecutionException 如果在可调用的执行过程中遇到问题。如果是这样,它将包含call()
抛出的异常。通过将 Callable 提交给执行器,您实际上是在要求它执行(异步)。无需采取进一步行动。只需检索未来并等待即可。
关于解决方案
虽然您的解决方案可以工作,但这不是很干净的代码,因为您劫持了 Call 的返回值。尝试这样的事情:
When you call
submit
, you are passing an object. You are not callingcall()
.EDIT
Submit
returns a Future f. When you callf.get()
, the method can throw an ExecutionException if a problem is encountered during the execution of the callable. If so, it will contain the exception thrown bycall()
.By submitting your Callable to the executor, you are actually asking it to execute it (asynchronously). No need for further action. Just retrieve the future and wait.
ABOUT THE SOLUTION
Although your solution will work, this not very clean code, because you are hijacking the return value of Call. Try something like this:
提交方法不会抛出 SQLException。
The submit method does not throw a SQLException.
这是因为爬虫永远不会抛出 SQLException。
尝试使用
finally
而不是catch
并查看是否会遇到问题或是否有效。It's because SQLException never will be throw by the crawler.
Try use
finally
instead ofcatch
and see if you will have a problem or it works.你使用什么IDE?当我尝试你的代码时,Eclipse 抱怨“未处理的异常类型异常”。这是有道理的,因为
Callable
接口定义了call()
方法来抛出Exception
。仅仅因为您的实现类声明了更受限制的异常类型,调用程序就不能依赖它。它希望您捕获异常。What IDE are you using? When I try your code, Eclipse complains "unhandled exception type Exception". This makes sense because the
Callable
interface defines thecall()
method to throwException
. Just because your implementation class declares a more restricted exception type, the calling program cannot count on that. It expects you to catch Exception.