2017-04-11 35 views
1

但是,testCase2不處理異常並引發錯誤。我錯過了什麼嗎?對不起,如果我這樣做,這是相當新的。期望從這兩個CompletableFutures獲得相同結果

@Test 
public void testCase1() throws Exception { 
    CompletableFuture.supplyAsync(() -> { 
     if (true) throw new RuntimeException(); 
     return "Promise"; 
    }).exceptionally((ex) -> { 
     return "Fake Promise"; 
    }).get(); 
} 

@Test 
public void testCase2() throws Exception { 
    CompletableFuture<String> cf = CompletableFuture.supplyAsync(() -> { 
     if (true) throw new RuntimeException(); 
     return "Promise"; 
    }); 
    cf.exceptionally((ex) -> { 
     return "Fake Promise"; 
    }); 
    cf.get(); 
} 

回答

2

然而testCase2不處理異常

testCase2沒有處理的異常,你可以添加額外的print語句來檢查它。

原因testCase2拋出一個例外是,代碼:

cf.exceptionally((ex) -> { 
     System.out.println("Fake Promise: " + System.nanoTime()); 
     return "Fake Promise"; 
    }) 

將返回一個新CompletableFuture但你放棄吧,cf.get變量cf仍然沒有任何異常處理程序註冊。代碼應該是:

@Test 
public void testCase2() throws Exception { 
    CompletableFuture<String> cf = CompletableFuture.supplyAsync(() -> { 
     if (true) throw new RuntimeException(); 
     return "Promise"; 
    }); 
    CompletableFuture<String> handledCf = cf.exceptionally((ex) -> { 
     return "Fake Promise"; 
    }); 
    return handledCf.get(); 
} 
+0

謝謝。我感到很愚蠢。 :/ – slee

+0

沒有什麼大不了的,只是每個人在學習時都會犯的一些常見錯誤:-) – shizhz

相關問題