In Java, the Optional object is a container object which may or may not contain a value. We can replace the multiple null check using the Optional object’s isPresent method.
The
Optionalclass is present in thejava.utilpackage. Read more about theOptionalclass here.
The orElseThrow method will return the value present in the Optional object. If the value is not present, then the supplier function passed as an argument is executed and an exception created on the function is thrown.
public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X extends Throwable
The argument is the function to be executed if the Optional object is Optional object
If the Optional object contains a value, then the value is returned. Otherwise, the exception created by the supplier function is returned.
This method throws
NullPointerExceptionif no value is present and the supplier function isnull.
The below code denotes how to use the orElseThrow method.
import java.util.Optional;class OptionalOrElseThrowExample {public static void main(String[] args) throws Exception{Optional<Integer> optional1 = Optional.of(1);System.out.println("Optional1 : " + optional1);Integer val = optional1.orElseThrow(()-> {return new Exception("no value present in Optional object");});System.out.println("Value at Optional1 is : " + val);Optional<Integer> optional2 = Optional.empty();System.out.println("\nOptional2 : " + optional2);val = optional2.orElseThrow(()-> {return new Exception("no value present in Optional object");});}}
In the above code:
In line number 1, we import the Optional class.
In line number 5, we create an Optional object of the Integer type with value 1 using of method.
In line number 7, we call the orElseThrow method on the optional1 object. For the orElseThrow method, a supplier function that returns an Exception object is passed as an argument. This method returns 1 because the optional1 object contains the value.
In line number 12, we use the empty method to get an empty Optional object of the Integer type. The returned object doesn’t have any value.
In line number 12, we call the orElseThrow method on the optional2 object. For the orElseThrow method, a supplier function that returns an Exception object is passed as an argument. This method throws the Exception returned by the supplier function because the optional2 object doesn’t have any value.