Şu satırı dahil ederiz
import java.util.concurrent.CompletionException;
- Bir CompletableFuture'a get() yaparsak ve CompletableFuture exception ile biterse, ExecutionException fırlatılır.
Örnek - ArithmeticException
Örnek - ArithmeticException
Şöyle yaparız
CompletableFuture<Void> completableFuture = CompletableFuture .supplyAsync(() -> { System.out.println("running task"); return 1 / 0; }) .thenApply(input -> { System.out.println("multiplying by 2"); return input * 2; }) .thenAccept(System.out::println); Thread.sleep(3000);//let the stages complete System.out.println("-- checking exceptions --"); try { completableFuture.join(); } catch (CompletionException exception) { exception.printStackTrace(); } //compile error //} catch (ExecutionException exception) { // exception.printStackTrace(); //}printStackTrace() çıktısı şöyle. "Caused by" kısmında exception'ının hangi satırdan geldiği gösteriliyor.
java.util.concurrent.CompletionException: java.lang.ArithmeticException: / by zero at java.util.concurrent.CompletableFuture.encodeThrowable(CompletableFuture.java:273) at java.util.concurrent.CompletableFuture.completeThrowable(CompletableFuture.java:280) at java.util.concurrent.CompletableFuture$AsyncSupply.run$$$capture(CompletableFuture.java:1606) at java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java) at java.util.concurrent.CompletableFuture$AsyncSupply.exec(CompletableFuture.java:1596) at java.util.concurrent.ForkJoinTask.doExec$$$capture(ForkJoinTask.java:289) at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java) at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1056) at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692) at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:175) Caused by: java.lang.ArithmeticException: / by zero at Scratch.lambda$join$0(scratch.java:13) at java.util.concurrent.CompletableFuture$AsyncSupply.run$$$capture(CompletableFuture.java:1604) ... 7 moreÖrnek - completeExceptionally
Şöyle yaparız
CompletableFuture<Double> completableFuture = CompletableFuture .supplyAsync(() -> { System.out.println("running task"); return 2.0; }); completableFuture.completeExceptionally(new RuntimeException("my error")); Thread.sleep(3000);//let the stages complete System.out.println("-- checking exceptions --"); try { completableFuture.join(); } catch (CompletionException exception) { exception.printStackTrace(); }
printStackTrace() çıktısı şöyle. "Caused by" kısmında exception'ının hangi satırdan geldiği gösteriliyor.
java.util.concurrent.CompletionException: java.lang.RuntimeException: my error at java.util.concurrent.CompletableFuture.reportJoin(CompletableFuture.java:375) at java.util.concurrent.CompletableFuture.join(CompletableFuture.java:1947) at Scratch.join2(scratch_6.java:49) at Scratch.main(scratch_6.java:83) Caused by: java.lang.RuntimeException: my error at Scratch.join2(scratch.java:43) ... 1 more
Hiç yorum yok:
Yorum Gönder