Next() of an iterator neither checks for the end nor delegates, so it fails with the wrong exception

tx0/java:iterator-next-without-endrecommendedwarningbug

What it finds

The contract of Iterator.next() is to throw NoSuchElementException when there are no more elements, and callers such as for loops over a Spliterator and Guava's helpers rely on that exception. A next() that just returns items[index++] throws an ArrayIndexOutOfBoundsException instead, or returns garbage.

Reported is next() without parameters in a class that implements Iterator or ListIterator, whose body contains no throw and calls no method that could check for the end.

From the rule's source, iterator_next_without_end.rs.

Example from the rule's tests
import java.util.Iterator;import java.util.NoSuchElementException; class Items implements Iterator<String> {  private final String[] items = new String[0];  private int index;   public boolean hasNext() {    return index < items.length;  }   public String next() {tx0 reports: never throws NoSuchElementException    return items[index++];  }} class Checked implements Iterator<String> {  private int index;   public boolean hasNext() {    return index < 3;  }   public String next() {    if (index >= 3) {      throw new NoSuchElementException();    }    index++;    return "";  }}
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/java:iterator-next-without-end" = "warning"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

// tx0: ignore[tx0/java:iterator-next-without-end] reason="..."

tx0 explain tx0/java:iterator-next-without-end shows the same in the terminal. Found a false positive? Report it.