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

  1. Always guard with hasNext() before next()
  2. Use the enhanced for-loop / stream APIs instead of manual next() calls
  3. Track remaining count if index-based logic must be used
  4. 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

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


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)