Java在异步线程中不显示运行时错误/异常。

huangapple go评论95阅读模式
英文:

Java not showing runtime errors/exceptions on async threads

问题

我有异步运行的 SQL 查询,使用以下代码:

CompletableFuture.runAsync(() -> {
        readFromDB();
        parseJSON();
    });

没有错误/异常显示出来,我甚至尝试抛出随机异常 (throw new EmptyStackException();),但在控制台中没有显示出来,printf() 正常工作。

为什么错误/异常没有显示出来?

英文:

I have sql queries that run asynchronously using

CompletableFuture.runAsync(() -> {
        readFromDB();
        parseJSON();
    });

And no errors/exceptions are showing up, I even tried throwing random exception (throw new EmptyStackException();) and it doesn't show up in the console, printf() is working normally.

Why are errors/exceptions not showing up?

答案1

得分: 2

这是设计如此。要捕获/处理异常,需要一个同步点。通过调用 CompletableFuture.runAsync(...),执行明确地与当前线程解耦,因此没有同步点。

相反,可以将创建的 CompletableFuture 存储起来并获取其状态,例如通过调用 join()

final CompletableFuture<Void> future = CompletableFuture.runAsync(...);
...
try {
    future.join(); // 如果有异常,这将重新抛出未来中发生的异常
} catch (final RuntimeException e) { 
    e.printStackTrace();
}
英文:

This is by design. To catch/handle an exception, one needs a synchronization point. By calling CompletableFuture.runAsync(...) the execution is explicitly decoupled from the current thread and thus has no synchronization point.

What one can do instead is store the created CompletableFuture and get its status, e.g. by calling join():

final CompletableFuture&lt;Void&gt; future = CompletableFuture.runAsync(...);
...
try {
    future.join(); // This will re-throw the exception that occured in the future, if any
} catch (final RuntimeException e) { 
    e.printStackTrace();
}

答案2

得分: 1

替代runAsync,您可以使用supplyAsync(()->并且处理异常,类似于:

 supplyAsync(()-> {
         从数据库读取();
         解析JSON();
    })
    .exceptionally(e-> {
         // 在这里写入您的逻辑
    });
英文:

Instead of runAsync, you can use supplyAsync(()-> and handle exception something like:

 supplyAsync(()-&gt; {
         readFromDB();
         parseJSON();
    })
    .exceptionally(e-&gt; {
         // your logic here
    });

huangapple
  • 本文由 发表于 2020年7月26日 03:14:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/63092503.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定