In Java, the OptionalInt
object is a container object that may or may not contain an integer
value.
The
OptionalInt
class is present in thejava.util
package.
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.
public <X extends Throwable> int orElseThrow(Supplier<? extends X> exceptionSupplier) throws X extends Throwable
The argument is the function to be executed if the OptionalInt
object is OptionalInt
object
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
NullPointerException
if no value is present and the supplier function isnull
.
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");});}}
In the code above:
In line 1, we imported the OptionalInt
class.
In line 5, we created an OptionalInt
object with a value of 1
using the of
method.
In line 7, we called 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 12, we used the empty
method to get an empty OptionalInt
object. The returned object doesn’t have any value.
In line 13, we called 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 a value.