clojure/clojure · error · java.util.NoSuchElementException

NoSuchElementException

Error message

NoSuchElementException

What it means

EmptyList's iterator is a sentinel: hasNext() is always false, so next() has no element and throws NoSuchElementException per the Iterator contract. Fires only when client code violates the contract by calling next() after hasNext() returned false.

Solutions

  1. Check hasNext() before calling next().
  2. Handle the empty-collection case before iterating.
  3. Prefer for-each loops, which skip iteration entirely for empty collections.

Example fix

// before
Object first = it.next();
// after
Object first = it.hasNext() ? it.next() : null;
Defensive patterns

Strategy: type-guard

Validate before calling

if (lst.isEmpty()) return;

Type guard

Object safeNext(java.util.Iterator<?> it) { return it.hasNext() ? it.next() : null; }

Try / catch

try { e = it.next(); } catch (java.util.NoSuchElementException ex) { e = null; }

Prevention

When it happens

Trigger: Calling next() on the iterator of '() (PersistentList/EmptyList) without a hasNext() check.

Common situations: Java interop loops over an empty list, or generic collection-processing code that assumes non-empty input.

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 clojure/clojure@f3b143341d (2026-09-09). Data as JSON: /api/errors/92ac8b39ebda562d. Report an issue: GitHub.

Appendix: source

Thrown at src/jvm/clojure/lang/PersistentList.java:243

	}

	public boolean isEmpty(){
		return true;
	}

	public boolean contains(Object o){
		return false;
	}

	public Iterator iterator(){
		return new Iterator(){

			public boolean hasNext(){
				return false;
			}

			public Object next(){
				throw new NoSuchElementException();
			}

			public void remove(){
				throw new UnsupportedOperationException();
			}
		};
	}

	public Object[] toArray(){
		return RT.EMPTY_ARRAY;
	}

	public boolean add(Object o){
		throw new UnsupportedOperationException();
	}

	public boolean remove(Object o){
		throw new UnsupportedOperationException();

View on GitHub (pinned to f3b143341d)