Java 25 (LTS) reference · Optional

Java Optional orElseThrow() Method

Return the value if present, otherwise throw: NoSuchElementException by default, or an exception you supply.

Java 25 (LTS) Since Java 10

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

optional.orElseThrow(exceptionSupplier)

Parameters

ParameterDescription
exceptionSupplier optional
Supplier<X>
Creates the exception to throw.

Return value

The value.

Examples

Get a value that must exist
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Map<Integer, String> users = Map.of(1, "Ana");
        String name = Optional.ofNullable(users.get(1)).orElseThrow();
        System.out.println(name);
    }
}

Output

Ana

Run this on your computer — see “Get Started” for setup.

A custom exception
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Map<Integer, String> users = Map.of(1, "Ana");
        try {
            Optional.ofNullable(users.get(9)).orElseThrow(() -> new IllegalArgumentException("user 9 not found"));
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
    }
}

Output

user 9 not found

Run this on your computer — see “Get Started” for setup.

Version history

VersionChange
Java Java 10Added

Was this page helpful?