3 回答

TA貢獻1802條經驗 獲得超5個贊
該方法foo不得拋出已檢查的異常,而是不可聲明的 RuntimeException。
class MyException extends RuntimeException
創建 Future 已經不執行foo,將在另一個調用中執行。所以不能扔任何東西。
private static CompletableFuture<String> test() {
return CompletableFuture.supplyAsync(() -> foo("b"));
}
可以通過超時get()或get超時等待完成。這將通過將其MyException包裝為ExecutionException.
嘗試 { 測試()。get();} catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.getCause().printStackTrace(); }
不要忘記攔截異常exceptionally:
try {
String s = test().exceptionally(throwable -> {
throwable.getCause().printStackTrace();
return "xxx"; }).get();
System.err.println("s=" + s);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}

TA貢獻1877條經驗 獲得超6個贊
您需要在 CompletableFuture 的實現中提供此已檢查的 MyException 異常,因為它是“已檢查的異?!?,這意味著它是從 Exception 類派生的。要么為它提供服務,要么將 MyException 更改為從 RuntimeException 擴展,那么您就不需要提供它(捕獲它)。
添加回答
舉報