我运行了一些代码CompletableFuture
并想处理调用它的代码中的错误。但是 catch 不起作用,我做错了什么?
try {
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
throw new IllegalStateException("Error");
});
} catch (IllegalStateException e) {
System.out.println("Expected Error: " + e.getMessage());
}
附言:我知道supplyAsync
和exceptionally
,但这个选项不适合我
try-catch
它在这里不起作用,因为CompletableFuture.runAsync
它在另一个线程中运行代码,并且那里的异常不会进入您的catch
。要处理错误,您需要明确等待 CompletableFuture 完成,例如通过
join()
或get()
。只有这样才有可能捕获异常,但已经包裹在中CompletionException
,并且必须通过小心地解包getCause()