stanfordnlp/CoreNLP · error · NoSuchElementException
TreeIterator exhausted
Error message
TreeIterator exhausted
What it means
Tree's iterator throws NoSuchElementException with this message when next() is called after the traversal stack is empty. This is the standard Java iterator contract; the message just identifies which iterator was over-advanced.
Solutions
- Guard every next() with iterator.hasNext() (or use an enhanced for-loop over the tree)
- Do not reuse an exhausted TreeIterator; obtain a fresh iterator() call
- Make sure each iteration consumes exactly one next() call
Example fix
// before
while (true) { Tree t = it.next(); ... } // exhausts
// after
while (it.hasNext()) { Tree t = it.next(); ... } Defensive patterns
Strategy: type-guard
Validate before calling
if (!it.hasNext()) return null; Tree t = it.next();
Type guard
Tree nextOrNull(Iterator<Tree> it) { return it.hasNext() ? it.next() : null; } Try / catch
try { Tree t = it.next(); } catch (NoSuchElementException e) { /* iterator exhausted; stop loop */ } Prevention
- Always loop on hasNext() or use for (Tree t : tree)
- Never call next() twice per loop iteration
- Create a fresh iterator per traversal
When it happens
Trigger: Calling next() more times than there are nodes — typically a loop that calls next() without hasNext(), or reusing an exhausted iterator.
Common situations: Manual while-loops calling it.next() twice per iteration; nested iteration over the same iterator; storing next() results in two variables from a single call site.
Understand the failure class
Background: EmptyResultError / "no results found": when an API or scraper succeeds but returns zero rows — this error's family across 9 libraries.
Related errors
- DocumentIterator exhausted.
- No more elements from
- Can't set Tree labels
- ancestor: height cannot be negative
- Tree.valueOf() tree construction failed
AI-assisted analysis of stanfordnlp/CoreNLP@1b7edd19c4 (2026-09-10).
Data as JSON: /api/errors/a5d8d0e6da093573.
Report an issue: GitHub.
Appendix: source
Thrown at src/edu/stanford/nlp/trees/Tree.java:2313
private static class TreeIterator implements Iterator<Tree> {
private final List<Tree> treeStack;
protected TreeIterator(Tree t) {
treeStack = new ArrayList<>();
treeStack.add(t);
}
@Override
public boolean hasNext() {
return (!treeStack.isEmpty());
}
@Override
public Tree next() {
int lastIndex = treeStack.size() - 1;
if (lastIndex < 0) {
throw new NoSuchElementException("TreeIterator exhausted");
}
Tree tr = treeStack.remove(lastIndex);
Tree[] kids = tr.children();
// so that we can efficiently use one List, we reverse them
for (int i = kids.length - 1; i >= 0; i--) {
treeStack.add(kids[i]);
}
return tr;
}
/**
* Not supported
*/
@Override
public void remove() {
throw new UnsupportedOperationException();
}
View on GitHub (pinned to 1b7edd19c4)