// concurrent/CompletableExceptions.java// (c)2017 MindView LLC: see Copyright.txt// We make no guarantees that this code is fit for any purpose.// Visit http://OnJava8.com for more book information.import java.util.concurrent.*;public class CompletableExceptions {static CompletableFuture<Breakable>test(String id, int failcount) {returnCompletableFuture.completedFuture(new Breakable(id, failcount)).thenApply(Breakable::work).thenApply(Breakable::work).thenApply(Breakable::work).thenApply(Breakable::work);}public static void main(String[] args) {// Exceptions don't appear ...test("A", 1);test("B", 2);test("C", 3);test("D", 4);test("E", 5);// ... until you try to fetch the value:try {test("F", 2).get(); // or join()} catch(Exception e) {System.out.println(e.getMessage());}// Test for exceptions:System.out.println(test("G", 2).isCompletedExceptionally());// Counts as "done":System.out.println(test("H", 2).isDone());// Force an exception:CompletableFuture<Integer> cfi =new CompletableFuture<>();System.out.println("done? " + cfi.isDone());cfi.completeExceptionally(new RuntimeException("forced"));try {cfi.get();} catch(Exception e) {System.out.println(e.getMessage());}}}/* Output:Throwing Exception for ABreakable_B [1]Throwing Exception for BBreakable_C [2]Breakable_C [1]Throwing Exception for CBreakable_D [3]Breakable_D [2]Breakable_D [1]Throwing Exception for DBreakable_E [4]Breakable_E [3]Breakable_E [2]Breakable_E [1]Breakable_F [1]Throwing Exception for Fjava.lang.RuntimeException: Breakable_F failedBreakable_G [1]Throwing Exception for GtrueBreakable_H [1]Throwing Exception for Htruedone? falsejava.lang.RuntimeException: forced*/
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。