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 Optional class is present in the java.util package. Read more about the Optional class 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 emptyno value present in the Optional object. The supplier function should return the exception to be thrown.

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 NullPointerException if no value is present and the supplier function is null.

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 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.