NoSuchElementException When Exhausted
What you'll learn: You'll discover what happens when you call next() on an iterator that has no more elements to return.
The Core Idea
When working with an Iterator, you must always check hasNext() before calling next(). If you call next() after hasNext() has returned false—meaning the iterator is exhausted—Java throws a NoSuchElementException. This is a runtime exception that signals you've tried to retrieve an element that doesn't exist.
Think of an iterator like flipping through pages in a book. The hasNext() method tells you "Are there more pages?" and next() turns to the next page. If you try to turn the page when you've already reached the back cover, you'll encounter an error—there's simply nothing left to read.
The Safe Pattern
Always use this pattern to avoid the exception:
Iterator<String> iter = list.iterator();
while (iter.hasNext()) {
String element = iter.next(); // Safe: hasNext() checked first
System.out.println(element);
}
What Not to Do
Iterator<String> iter = list.iterator();
iter.next(); // First element - OK if list isn't empty
iter.next(); // Second element - OK if list has 2+ elements
iter.next(); // NoSuchElementException if list had only 2 elements!
Calling next() without checking hasNext() first is risky. The moment you go past the last element, the exception is thrown.
Why This Design?
The exception serves as a safety mechanism—it alerts you immediately when you've violated the iterator contract, making bugs easier to catch during development.
Key Takeaway: Always call hasNext() before next() to avoid NoSuchElementException; calling next() on an exhausted iterator is a programming error that throws an unchecked exception.