Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Optional.orElseThrow: practical reference

Optional.orElseThrow: practical reference: Optional.orElseThrow returns the present value; the no-argument form throws NoSuchElementException when empty, while the supplier form throws the supplied exception.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

Optional.orElseThrow(...)

Optional.orElseThrow returns the present value; the no-argument form throws NoSuchElementException when empty, while the supplier form throws the supplied exception.

Use it when absence violates the method contract; the supplier can lazily construct a domain exception, including a checked exception.

The exception supplier is not invoked for a present value, so do not place work there that must happen regardless of absence.

For an empty Optional, a null supplier causes NullPointerException; a supplier producing null likewise leads to NullPointerException when thrown.

The example exercises the documented element in a small deterministic program and compares exact standard output.

Examples

public class Main {
    public static void main(String[] args) throws Exception {
        try {
            java.util.Optional.empty().orElseThrow();
        } catch (java.util.NoSuchElementException error) {
            System.out.println(error.getClass().getSimpleName());
        }
    }
}

Result

NoSuchElementException

The example exercises the documented element in a small deterministic program and compares exact standard output.

Sources