Java : NoSuchElementException with Examples

NoSuchElementException (Java SE 21 & JDK 21) with Examples.
You will find code examples on most NoSuchElementException methods.


Summary

Thrown by various accessor methods to indicate that the element being requested does not exist.

Class diagram

// Bad
final var list = List.<String>of();
try {
    final var value = list.getFirst();
} catch (NoSuchElementException e) {
    System.out.println("NoSuchElementException!");
}

// Result
// ↓
//NoSuchElementException!

// Good
if (!list.isEmpty()) {
    System.out.println("value : " + list.getFirst());
} else {
    System.out.println("Empty!");
}

// Result
// ↓
//Empty!
// Bad
final var opt = Optional.<String>empty();
try {
    final var value = opt.orElseThrow();
} catch (NoSuchElementException e) {
    System.out.println("NoSuchElementException! : " + e.getMessage());
}

// Result
// ↓
//NoSuchElementException! : No value present

// Good
if (opt.isPresent()) {
    System.out.println("value : " + opt.orElseThrow());
} else {
    System.out.println("Empty!");
}

// Result
// ↓
//Empty!

Constructors

NoSuchElementException ()

Constructs a NoSuchElementException with null as its error message string.

final var e = new NoSuchElementException();
System.out.println(e); // java.util.NoSuchElementException

NoSuchElementException (String s)

Constructs a NoSuchElementException, saving a reference to the error message string s for later retrieval by the getMessage method.

final var e = new NoSuchElementException("abcd");
System.out.println(e); // java.util.NoSuchElementException: abcd
System.out.println(e.getMessage()); // abcd

NoSuchElementException (String s, Throwable cause)

Constructs a NoSuchElementException with the specified detail message and cause.

final var cause = new IllegalStateException("XYZ");
final var e = new NoSuchElementException("abcd", cause);

System.out.println(e); // java.util.NoSuchElementException: abcd
System.out.println(e.getMessage()); // abcd

System.out.println(e.getCause()); // java.lang.IllegalStateException: XYZ
System.out.println(e.getCause().getMessage()); // XYZ

NoSuchElementException (Throwable cause)

Constructs a NoSuchElementException with the specified cause.

final var cause = new IllegalStateException("XYZ");
final var e = new NoSuchElementException(cause);

System.out.println(e); // java.util.NoSuchElementException: java.lang.IllegalStateException: XYZ
System.out.println(e.getMessage()); // java.lang.IllegalStateException: XYZ

System.out.println(e.getCause()); // java.lang.IllegalStateException: XYZ
System.out.println(e.getCause().getMessage()); // XYZ

Methods declared in Throwable

addSuppressed, fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, getSuppressed, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString

Please see the link below.


Related posts

To top of page