In Java, the OptionalInt
object is a container object that may or may not contain an integer
value.
The OptionalInt
class is present in the java.util
package.
orElseThrow()
methodThe orElseThrow
method returns the long
value present in the OptionalLong
object.
If the value is not present, then the supplier function passed as an argument is executed and an exception is returned on the function that is thrown.
public <X extends Throwable> long orElseThrow(Supplier<? extends X> exceptionSupplier) throws X extends Throwable
The orElseThrow
method accepts the function to be executed if the OptionalLong
object is empty (no value present in the Optional
object) as an argument.
The supplier function should return the exception to be thrown.
If the OptionalLong
object contains a value, then the method returns the value. Otherwise, orElsethrow
returns the exception returned by the supplier function.
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.OptionalLong;class OptionalLongOrElseThrowExample {public static void main(String[] args) throws Exception{OptionalLong optional1 = OptionalLong.of(1);System.out.println("Optional1 : " + optional1);long val = optional1.orElseThrow(()-> {return new Exception("no value present in Optional object");});System.out.println("Value at Optional1 is : " + val);OptionalLong optional2 = OptionalLong.empty();System.out.println("\nOptional2 : " + optional2);val = optional2.orElseThrow(()-> {return new Exception("no value present in Optional object");});}}
In the code above:
Line 1: We import the OptionalLong
class.
import java.util.OptionalLong;
Line 5: We use the of
method to create an OptionalLong
object with value 1
.
OptionalLong optional1 = OptionalLong.of(1);
Line 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.
long val =
optional1.orElseThrow(()-> {
return new Exception("no value present in Optional object");
});
Line 12: We use the empty
method to get an empty OptionalLong
object. The returned object doesn’t have any value.
OptionalLong optional2 = OptionalLong.empty();
Line 14: 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 a value.
val = optional2.orElseThrow(()-> {
return new Exception("no value present in Optional object");
});
// exception is thrown