Iterator.next() Must Throw NoSuchElementException

ID

java.iterator_next_must_throw_nosuchelement

Severity

high

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Java

Tags

CWE:754, reliability

Description

Reports next() method implementations in classes that implement Iterator but do not throw NoSuchElementException when the iteration is exhausted.

Rationale

The Iterator.next() contract requires that a NoSuchElementException is thrown when no more elements are available. Omitting this check means the iterator may return null, throw an ArrayIndexOutOfBoundsException, or silently produce corrupt data when called past the end. Callers that rely on the standard contract (including enhanced for-loops and Streams) will behave unpredictably.

// Bad — no NoSuchElementException
class MyIterator implements Iterator<String> {
    private int i = 0;
    private String[] items;
    public boolean hasNext() { return i < items.length; }
    public String next() { return items[i++]; }
}

Remediation

Guard next() with a bounds check that throws NoSuchElementException:

// Good
public String next() {
    if (!hasNext()) {
        throw new NoSuchElementException();
    }
    return items[i++];
}