为什么没有抛出异常?

发布于 2024-12-11 06:31:40 字数 463 浏览 0 评论 0 原文

我有这段简单的代码:

@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,则异常会在块中捕获,但如果没有,则不会提前抛出异常,但不会发生错误。似乎它被锁定并且不再继续执行代码。

为什么会有这种行为?我误会了什么?这不是预期的事吗?

I have this simple piece of code:

@Override
public Object call() throws Exception {
    try (Connection conn = ConnectionPool.getConnection()) {
        pageDAO = new PageDAO(conn);
        linkDAO = new LinkDAO(conn);
        loopInsertion();
    }
    return true;
}

I'm getting a SQLException in the getConnection() method. If I put a catch, the exception is catched in the block, but if not, the Exception is not throwed ahead, but an error not occurs. Appears that it became locked and not continues the code execution.

Why this behavior? I misunderstood something? This is not expected to do?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

她如夕阳 2024-12-18 06:31:40

我猜测您尚未显示的代码,但如果这是 使用 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文