CompletableFuture.runAsync的异常如何不抛出
时间: 2023-10-13 12:21:17 浏览: 49
与CompletableFuture.supplyAsync()方法一样,如果你不想在使用CompletableFuture.runAsync()方法时抛出异常,可以使用exceptionally()方法来处理异常并返回一个默认值,而不是抛出异常。例如:
```
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
// 可能会抛出异常的代码
}).exceptionally(e -> {
System.out.println("发生异常:" + e);
return null;
});
```
在这个示例中,如果runAsync()方法中的代码抛出异常,exceptionally()方法中的代码将会被执行,并返回null作为默认值。如果没有抛出异常,runAsync()方法将正常执行,但是返回值为Void,因此返回值为null。