Thursday, October 2, 2025
HomeLanguagesJavaOptionalLong orElseThrow(Supplier) method in Java with examples

OptionalLong orElseThrow(Supplier) method in Java with examples

The orElseThrow(Supplier) method of OptionalLong class is used to get the long value contained by OptionalLong. 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> long 
    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:




// Java program to demonstrate
// OptionalLong.orElseThrow(Supplier) method
  
import java.util.OptionalLong;
  
public class GFG {
  
    public static void main(String[] args)
    {
  
        // create a OptionalLong
        OptionalLong opLong = OptionalLong.of(894763545123L);
  
        // apply orElseThrow(Supplier)
        long value = opLong.orElseThrow(ArithmeticException::new);
  
        System.out.println("value " + value);
    }
}


Output:

Program 2:




// Java program to demonstrate
// OptionalLong.orElseThrow(Supplier) method
  
import java.io.IOException;
import java.util.OptionalLong;
  
public class GFG {
  
    public static void main(String[] args)
    {
  
        // create a OptionalLong
        OptionalLong opLong = OptionalLong.empty();
  
        // apply orElseThrow(Supplier)
        Long value;
  
        try {
  
            value = opLong.orElseThrow(ArithmeticException::new);
        }
        catch (ArithmeticException e) {
            // TODO Auto-generated catch block
            System.out.println("Exception " + e);
        }
    }
}


Output:

References: https://docs.oracle.com/javase/10/docs/api/java/util/OptionalLong.html#orElseThrow(java.util.function.Supplier)

RELATED ARTICLES

Most Popular

Dominic
32331 POSTS0 COMMENTS
Milvus
85 POSTS0 COMMENTS
Nango Kala
6703 POSTS0 COMMENTS
Nicole Veronica
11867 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11926 POSTS0 COMMENTS
Shaida Kate Naidoo
6818 POSTS0 COMMENTS
Ted Musemwa
7079 POSTS0 COMMENTS
Thapelo Manthata
6775 POSTS0 COMMENTS
Umr Jansen
6776 POSTS0 COMMENTS