Created
September 22, 2022 21:41
-
-
Save viveknaskar/fc0b11e8c6c792ae47f70ab054454975 to your computer and use it in GitHub Desktop.
Illustration of exceptionally method of CompletableFuture
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
import java.util.concurrent.CompletableFuture; | |
import java.util.concurrent.ExecutionException; | |
public class ExceptionallyExample { | |
public static void main(String[] args) throws ExecutionException, InterruptedException { | |
int val = 0; | |
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> { | |
if(val == 0) { | |
throw new IllegalArgumentException("Value is 0"); | |
} | |
if(val > 0) { | |
return "Positive value!"; | |
} else { | |
return "Negative value!"; | |
} | |
}).exceptionally(ex -> { // printing error messages & returning a default value | |
System.out.println("Failed due: " + ex.getMessage()); | |
return "Default value!"; | |
}); | |
//get() blocks and gets the result of the Future | |
System.out.println(completableFuture.get()); | |
} | |
} | |
/*************************************************************************** | |
* Output: | |
* Failed due: java.lang.IllegalArgumentException: Value is 0 | |
* Default value! | |
**************************************************************************/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment