Friday, November 21, 2025
HomeLanguagesJavaOptionalInt orElseThrow(Supplier) method in Java with examples

OptionalInt orElseThrow(Supplier) method in Java with examples

The orElseThrow(Supplier) method of OptionalInt class used to get the value contained by OptionalInt. 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> int 
    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
// OptionalInt.orElseThrow(Supplier) method
import java.util.OptionalInt;
  
public class GFG {
  
    public static void main(String[] args)
    {
  
        // create a OptionalInt
        OptionalInt opint
            = OptionalInt.of(24);
  
        // apply orElseThrow(Supplier)
        int value
            = opint.orElseThrow(ArithmeticException::new);
  
        System.out.println("value " + value);
    }
}


Output:

Program 2:




// Java program to demonstrate
// OptionalInt.orElseThrow(Supplier) method
import java.io.IOException;
import java.util.OptionalInt;
  
public class GFG {
  
    public static void main(String[] args)
    {
  
        // create a OptionalInt
        OptionalInt opint
            = OptionalInt.empty();
  
        // apply orElseThrow(Supplier)
        int value;
  
        try {
  
            value
                = opint.orElseThrow(IOException::new);
        }
        catch (IOException e) {
  
            System.out.println("Exception " + e);
        }
    }
}


Output:

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

RELATED ARTICLES

2 COMMENTS

Most Popular

Dominic
32405 POSTS0 COMMENTS
Milvus
97 POSTS0 COMMENTS
Nango Kala
6781 POSTS0 COMMENTS
Nicole Veronica
11928 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11995 POSTS0 COMMENTS
Shaida Kate Naidoo
6907 POSTS0 COMMENTS
Ted Musemwa
7166 POSTS0 COMMENTS
Thapelo Manthata
6862 POSTS0 COMMENTS
Umr Jansen
6847 POSTS0 COMMENTS