|
| 1 | +// concurrent/CatchCompletableExceptions.java |
| 2 | +// (c)2016 MindView LLC: see Copyright.txt |
| 3 | +// We make no guarantees that this code is fit for any purpose. |
| 4 | +// Visit http://OnJava8.com for more book information. |
| 5 | +import java.util.concurrent.*; |
| 6 | +import onjava.Nap; |
| 7 | + |
| 8 | +public class CatchCompletableExceptions { |
| 9 | + static void handleException(int failcount) { |
| 10 | + // Call Function only if there's an exception, |
| 11 | + // Must produce same type as came in: |
| 12 | + CompletableExceptions |
| 13 | + .test("exceptionally", failcount) |
| 14 | + .exceptionally((ex) -> { // Function |
| 15 | + if(ex == null) |
| 16 | + System.out.println("I don't get it yet"); |
| 17 | + return new Breakable(ex.getMessage(), 0); |
| 18 | + }) |
| 19 | + .thenAccept(str -> |
| 20 | + System.out.println("result: " + str)); |
| 21 | + |
| 22 | + // Create a new result (recover): |
| 23 | + CompletableExceptions |
| 24 | + .test("handle", failcount) |
| 25 | + .handle((result, fail) -> { // BiFunction |
| 26 | + if(fail != null) |
| 27 | + return "Failure recovery object"; |
| 28 | + else |
| 29 | + return result + " is good"; |
| 30 | + }) |
| 31 | + .thenAccept(str -> |
| 32 | + System.out.println("result: " + str)); |
| 33 | + |
| 34 | + // Do something but pass the same result through: |
| 35 | + CompletableExceptions |
| 36 | + .test("whenComplete", failcount) |
| 37 | + .whenComplete((result, fail) -> { // BiConsumer |
| 38 | + if(fail != null) |
| 39 | + System.out.println("It failed"); |
| 40 | + else |
| 41 | + System.out.println(result + " OK"); |
| 42 | + }) |
| 43 | + .thenAccept(r -> |
| 44 | + System.out.println("result: " + r)); |
| 45 | + } |
| 46 | + public static void main(String[] args) { |
| 47 | + System.out.println("**** Failure Mode ****"); |
| 48 | + handleException(2); |
| 49 | + System.out.println("**** Success Mode ****"); |
| 50 | + handleException(0); |
| 51 | + } |
| 52 | +} |
| 53 | +/* Output: |
| 54 | +**** Failure Mode **** |
| 55 | +Breakable_exceptionally [1] |
| 56 | +result: Breakable_java.lang.RuntimeException: |
| 57 | +Breakable_exceptionally failed [0] |
| 58 | +Breakable_handle [1] |
| 59 | +result: Failure recovery object |
| 60 | +Breakable_whenComplete [1] |
| 61 | +It failed |
| 62 | +**** Success Mode **** |
| 63 | +Breakable_exceptionally [-1] |
| 64 | +Breakable_exceptionally [-2] |
| 65 | +Breakable_exceptionally [-3] |
| 66 | +Breakable_exceptionally [-4] |
| 67 | +result: Breakable_exceptionally [-4] |
| 68 | +Breakable_handle [-1] |
| 69 | +Breakable_handle [-2] |
| 70 | +Breakable_handle [-3] |
| 71 | +Breakable_handle [-4] |
| 72 | +result: Breakable_handle [-4] is good |
| 73 | +Breakable_whenComplete [-1] |
| 74 | +Breakable_whenComplete [-2] |
| 75 | +Breakable_whenComplete [-3] |
| 76 | +Breakable_whenComplete [-4] |
| 77 | +Breakable_whenComplete [-4] OK |
| 78 | +result: Breakable_whenComplete [-4] |
| 79 | +*/ |
0 commit comments