英文:
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<Void> 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(()-> {
readFromDB();
parseJSON();
})
.exceptionally(e-> {
// your logic here
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论