What is the Optional.orElseThrow method in Java?
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
Argument
The argument is the function to be executed if the Optional object is Optional object
Return value
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.
Code
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");});}}
Explanation
In the above code:
-
In line number 1, we import the
Optionalclass. -
In line number 5, we create an
Optionalobject of theIntegertype with value1usingofmethod. -
In line number 7, we call the
orElseThrowmethod on theoptional1object. For theorElseThrowmethod, a supplier function that returns anExceptionobject is passed as an argument. This method returns1because theoptional1object contains the value. -
In line number 12, we use the
emptymethod to get an emptyOptionalobject of theIntegertype. The returned object doesn’t have any value. -
In line number 12, we call the
orElseThrowmethod on theoptional2object. For theorElseThrowmethod, a supplier function that returns anExceptionobject is passed as an argument. This method throws the Exception returned by the supplier function because theoptional2object doesn’t have any value.