Home › Java exceptions › NoSuchElementException
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 presentExtends 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
- Calling
Optional.get()without checkingisPresent(). - Reading more tokens from a Scanner than the input has.
- Calling
iterator.next()withouthasNext(). - Taking the first element of an empty collection, for example after a filter removed everything.
How to fix it
- Use
orElse,orElseGetororElseThrow(() -> new MyException(...))instead ofget(). - Check
hasNext()beforenext(), or use for-each. - Check
isEmpty()before taking the first or last element, or usepeekandpollvariants that return null. - When absence is a legitimate business case, model it explicitly and return a result type rather than throwing.
Broken and fixed
User u = repo.findById(id).get(); // No value presentUser 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.