CKTIS / Java
NoSuchElementException — the requested element does not exist
NoSuchElementException is a java.util exception indicating that a requested element does not exist. For example, Iterator.next() throws it when the iterator has no remaining elements.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
import java.util.NoSuchElementException;
// message: String; cause: Throwable
new NoSuchElementException();
new NoSuchElementException(message);
new NoSuchElementException(message, cause);
new NoSuchElementException(cause);NoSuchElementException in java.util indicates that a requested element does not exist. It extends RuntimeException, so it is unchecked: the compiler does not require you to catch it or declare it in throws.
Iterator.next() throws this exception when the iteration has no remaining elements. It does not return null in that situation. In an ordinary loop, check hasNext() before retrieving another element; false means the iteration has ended.
Constructors accept no arguments, a String message, a Throwable cause, or both a message and a cause. The no-argument constructor sets the message to null; getMessage() retrieves the message. Both constructors accepting a cause have been available since Java 15.
The example first prints the only element safely, then deliberately calls next() after iteration ends. Catching the exception demonstrates the failure; it is not a replacement for checking hasNext() in an ordinary loop. A fixed label is printed instead of the exception message so that the expected output does not depend on that message.
Examples
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
public class Main {
public static void main(String[] args) {
Iterator<String> items = List.of("A").iterator();
while (items.hasNext()) {
System.out.println(items.next());
}
try {
items.next();
} catch (NoSuchElementException e) {
System.out.println("NoSuchElementException");
}
}
}
Result
A NoSuchElementException
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.