BackendBench
Coffee

Home › Java exceptions › NoSuchElementException

Unchecked exception · java.util

NoSuchElementException: causes and fixes

An element was requested from an empty or exhausted source: Optional.get, Iterator.next, Scanner or a collection.

What it looks like

java.util.NoSuchElementException: No value present

Extends RuntimeException in java.util.

What it means

It is thrown when you ask for something that is not there: Optional.get() on an empty Optional ("No value present"), Iterator.next() after the last element, Scanner.nextLine() with no more input, Deque.getFirst() or List.getFirst() on an empty collection, and stream.reduce(...).get() on an empty stream.

Common causes

How to fix it

  1. Use orElse, orElseGet or orElseThrow(() -> new MyException(...)) instead of get().
  2. Check hasNext() before next(), or use for-each.
  3. Check isEmpty() before taking the first or last element, or use peek and poll variants that return null.
  4. When absence is a legitimate business case, model it explicitly and return a result type rather than throwing.

Broken and fixed

fails
User u = repo.findById(id).get(); // No value present
works
User u = repo.findById(id)
        .orElseThrow(() -> new UserNotFoundException(id));

🔎 Unravel the failing code 🔎 Unravel the fix

In Spring and enterprise code

Spring Data repositories return Optional from findById. Throwing a domain exception with the id in the message is far easier to debug than "No value present".

Debug it faster

Paste the whole stack trace into the stack trace beautifier to hide framework frames, jump to the root cause and find the first line of your own code. It runs in your browser, so the trace never leaves your machine.

Frequently asked questions

Is NoSuchElementException a checked or unchecked exception?

NoSuchElementException is an unchecked exception (it extends RuntimeException), so you are not forced to catch it. Prevent it with validation, or handle it where the input enters the system.

Which package is NoSuchElementException in?

It lives in java.util, so the import is import java.util.NoSuchElementException;.

What is the first thing to check when I see NoSuchElementException?

Read the message and the first stack trace line in your own code. The usual causes are: Calling Optional.get() without checking isPresent(); and Reading more tokens from a Scanner than the input has.

Related exceptions

More tools you might need