OptionalDouble orElseThrow(Supplier) method in Java with examples
Last Updated :
27 May, 2019
The orElseThrow(Supplier) method of OptionalDouble class used to get the value contained by OptionalDouble. If a value is present, this method returns the value, otherwise, this method throws an exception produced by the exception supplying function. The exception Supplier function is passed as a parameter.
Syntax:
public <X extends Throwable> double
orElseThrow(Supplier<X> exceptionSupplier)
throws X extends Throwable
Parameters: This method accepts one parameter exceptionSupplier which is the supplying function that produces an exception to be thrown.
Return value: This method returns the value, if present.
Exception: This method throw following Exceptions:
- X – if no value is present.
- NullPointerException – if no value is present and the exception supplying function is null
- X extends Throwable
Below programs illustrate orElseThrow(Supplier) method:
Program 1:
import java.util.OptionalDouble;
public class GFG {
public static void main(String[] args)
{
OptionalDouble opDouble
= OptionalDouble.of( 0.268924 );
double value
= opDouble.orElseThrow(ArithmeticException:: new );
System.out.println( "value " + value);
}
}
|
Output:
Program 2:
import java.io.IOException;
import java.util.OptionalDouble;
public class GFG {
public static void main(String[] args)
{
OptionalDouble opDouble
= OptionalDouble.empty();
double value;
try {
value = opDouble.orElseThrow(IOException:: new );
}
catch (IOException e) {
System.out.println( "Exception " + e);
}
}
}
|
Output:
References: https://docs.oracle.com/javase/10/docs/api/java/util/OptionalDouble.html#orElseThrow(java.util.function.Supplier)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...