What is the OptionalInt.orElseThrow method in Java?
In Java, the OptionalInt object is a container object that may or may not contain an integer value.
The
OptionalIntclass is present in thejava.utilpackage.
The orElseThrow method will return the integer value present in the OptionalInt object. If the value is not present, then the supplier function passed as an argument is executed and an exception that was returned on the function is thrown.
Syntax
public <X extends Throwable> int orElseThrow(Supplier<? extends X> exceptionSupplier) throws X extends Throwable
Argument
The argument is the function to be executed if the OptionalInt object is OptionalInt object
Return value
If the OptionalInt object contains a value then the value is returned. Otherwise, the exception that was returned by the supplier function is returned.
This method throws
NullPointerExceptionif no value is present and the supplier function isnull.
Code
The code below denotes how to use the orElseThrow method.
import java.util.OptionalInt;class OptionalIntOrElseThrowExample {public static void main(String[] args) throws Exception{OptionalInt optional1 = OptionalInt.of(1);System.out.println("Optional1 : " + optional1);int val = optional1.orElseThrow(()-> {return new Exception("no value present in Optional object");});System.out.println("Value at Optional1 is : " + val);OptionalInt optional2 = OptionalInt.empty();System.out.println("\nOptional2 : " + optional2);val = optional2.orElseThrow(()-> {return new Exception("no value present in Optional object");});}}
Explanation
In the code above:
-
In line 1, we imported the
OptionalIntclass. -
In line 5, we created an
OptionalIntobject with a value of1using theofmethod. -
In line 7, we called 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 12, we used the
emptymethod to get an emptyOptionalIntobject. The returned object doesn’t have any value. -
In line 13, we called 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 a value.