Java SE API

Optional.orElseThrow()

Return the contained value or throw the supplied exception; declares throws X. Java SE API; example uses Java 21-compatible syntax.

Formal Syntax & Structure

java syntaxjava
<X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X

Parameters & Attributes

NameTypeDescription
exceptionSupplierSupplier<? extends X>Creates a failure for absence

Return Value

T

Return the contained value or throw the supplied exception; declares throws X.

Working Example

Example Snippetjava
import java.util.*;import java.util.stream.*;public class Main {    public static void main(String[] args) {        Map<String,Integer> stock = Map.of("A", 5);        for (String sku : List.of("A", "B")) {            try {                int quantity = Optional.ofNullable(stock.get(sku)).orElseThrow(() -> new IllegalArgumentException("Unknown SKU: " + sku));                System.out.println(quantity);            } catch (IllegalArgumentException ex) {                System.out.println(ex.getMessage());            }        }    }}
Java Reference