Exceptions: NoSuchElementException from an exhausted Iterator or an empty Optional

Calling next() on an Iterator with nothing left, or get() on an empty Optional, both throw NoSuchElementException; the exception name is shared but each call site makes the missing-element cause obvious.

Code
Iterator<String> it = List.of("only").iterator();
it.next();
try {
    it.next();
} catch (NoSuchElementException e) {
    System.out.println("Iterator: " + e.getClass().getSimpleName());
}
Optional<String> empty = Optional.empty();
try {
    empty.get();
} catch (NoSuchElementException e) {
    System.out.println("Optional: " + e.getClass().getSimpleName() + ": " + e.getMessage());
}
Output
Iterator: NoSuchElementException
Optional: NoSuchElementException: No value present
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms