为什么没有抛出异常?
我有这段简单的代码:
@Override
public Object call() throws Exception {
try (Connection conn = ConnectionPool.getConnection()) {
pageDAO = new PageDAO(conn);
linkDAO = new LinkDAO(conn);
loopInsertion();
}
return true;
}
我在 getConnection()
方法中收到 SQLException
。如果我放置了catch
,则异常会在块中捕获,但如果没有,则不会提前抛出异常,但不会发生错误。似乎它被锁定并且不再继续执行代码。
为什么会有这种行为?我误会了什么?这不是预期的事吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我猜测您尚未显示的代码,但如果这是 使用 rel="nofollow">an ExecutorService,Callable 代码中发生的任何异常都不会传播到任何地方,直到您调用 方法之一href="http://download.oracle.com/javase/6/docs/api/java/util/concurrent/Future.html" rel="nofollow">当您 href="http://download.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html#submit%28java.util.concurrent.Callable%29" rel="nofollow">已提交这可调用。当您调用 get() 时,它将抛出 ExecutionException ,其根本原因是从代码中抛出的异常。
更简单地说,当您使用 ExecutorService 将代码分叉到另一个线程时,从该代码引发的任何异常都会被捕获并保留,直到您返回并询问运行代码的结果。如果你从不这样做,那么异常就会消失。
I'm guessing about the code that you haven't shown, but if this is a Callable that you invoke with an ExecutorService, any exception that happens inside the Callable code won't be propagated to anywhere until you call one of the get() methods on the Future that was returned when you submitted the Callable. When you invoke get(), it will throw an ExecutionException whose root cause is the exception that was thrown from your code.
To put it more simply, when you fork code to another thread using an ExecutorService, any exception thrown from that code is caught and held until you come back and ask for the result of running the code. If you never do, then the exception just disappears.