karatelabs/karate · error · NoSuchElementException
NoSuchElementException (iterator exhausted)
Error message
NoSuchElementException (iterator exhausted)
What it means
DiskBackedIterator.next() throws java.util.NoSuchElementException when nextLine is null, i.e. hasNext() reported exhaustion. This is the standard Iterator contract: calling next() past the end of the list.
Solutions
- Always guard with hasNext() before next()
- Use the enhanced for-loop / stream APIs instead of manual next() calls
- Track remaining count if index-based logic must be used
- Treat NoSuchElementException as an iteration-bug signal, not a data problem
Example fix
// before
while (true) { process(it.next()); } // exhausts
// after
while (it.hasNext()) { process(it.next()); } Defensive patterns
Strategy: try-catch
Validate before calling
// hasNext() gate before next()
if (it.hasNext()) { Object v = it.next(); } Type guard
Object nextOrNull(java.util.Iterator<?> it) { return it.hasNext() ? it.next() : null; } Try / catch
try { return it.next(); } catch (NoSuchElementException e) { return null; } // treat as end of iteration Prevention
- Always call hasNext() before next()
- Prefer for-each loops which cannot over-advance
- Do not assume element counts; derive bounds from the iterator itself
When it happens
Trigger: Calling next() more times than there are elements; calling next() without checking hasNext() when the flag-based hasNext has already returned false; loops that assume a fixed element count larger than the actual size.
Common situations: Off-by-one loops; manual iteration without hasNext checks; assuming the disk-backed list size matches another collection's size.
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
- NoSuchElementException
- sizeOf() needs one argument
- valuesOf() needs one argument
- index: , size
- temp file not found
AI-assisted analysis of karatelabs/karate@a22eb90246 (2026-09-12).
Data as JSON: /api/errors/95fae125c977a9c0.
Report an issue: GitHub.
Appendix: source
Thrown at karate-core/src/main/java/io/karatelabs/match/DiskBackedList.java:270
nextLine = reader.readLine();
if (nextLine == null) {
closeReader();
return false;
}
return true;
} catch (IOException e) {
closeReader();
throw new RuntimeException("failed to read next line", e);
}
}
@Override
public Object next() {
if (!hasNextCalled) {
hasNext();
}
if (nextLine == null) {
throw new NoSuchElementException();
}
hasNextCalled = false;
currentIndex++;
return deserializeItem(nextLine);
}
private void closeReader() {
try {
reader.close();
} catch (IOException e) {
logger.warn("failed to close reader: {}", e.getMessage());
}
}
}
}
View on GitHub (pinned to a22eb90246)