Created
November 8, 2016 17:36
-
-
Save mrsarm/8092bf0fbc3e01433b77de6e35af923c to your computer and use it in GitHub Desktop.
Java 8+ CompletableFuture example with error handling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CompletableFuture.supplyAsync(()-> { | |
try { | |
Thread.sleep(5000); | |
} catch (InterruptedException e) { | |
throw new RuntimeException("Error sleeping", e); | |
} | |
if (System.currentTimeMillis()%2==0) { | |
throw new RuntimeException("Even time..."); // 50% chance to fail | |
} | |
return "Hello World!"; | |
}) | |
.thenAcceptAsync(s-> { | |
System.out.println("Result: " + s); | |
}) | |
.exceptionally(e-> { | |
System.err.println("Error greeting: " + e.getMessage()); | |
return null; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@gaurav9822 no, because it's async code, but if you are building a "service" class and you want the caller to take care of the errors, you should remove the
exceptionally
block and maybe thethenAcceptAsync
block, and return theCompletableFuture
object returned bysupplyAsync
, so once the caller call your service method, it can handle the exception. Eg.Then in the caller: