Java : NoSuchElementException with Examples
NoSuchElementException (Java SE 21 & JDK 21) with Examples.
You will find code examples on most NoSuchElementException methods.
Summary
// 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 ()
final var e = new NoSuchElementException();
System.out.println(e); // java.util.NoSuchElementException
NoSuchElementException (String s)
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)
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)
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
- API Examples
- Error
- Exception
- RuntimeException
- ArithmeticException
- ArrayIndexOutOfBoundsException
- ArrayStoreException
- CancellationException
- ClassCastException
- ConcurrentModificationException
- DateTimeException
- DateTimeParseException
- IllegalArgumentException
- IllegalStateException
- IndexOutOfBoundsException
- NullPointerException
- PatternSyntaxException
- StringIndexOutOfBoundsException
- UnsupportedOperationException
- Throwable