2017-04-11 33 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

相关问题