java.util.NoSuchElementException

java.util.NoSuchElementException is a RuntimeException or say an UncheckedException and therefore it does not need to be declared in a constructor’s or a method’s throw block.

java.util.NoSuchElementException is usually thrown when we try to access some element which is not present or reserved for the underlying data structure in the heap, and, thrown by the different classes, which have method to fetch the next element or next tokens, like Iterator :: next(), Enumeration :: nextElement() , StringTokenizer :: nextToken().
Example
When we are iterating over hashmap without implementing the condition to check if there is any element or not, this exception is raised or thrown by Java, now this is the reason we use hasNext() before calling next() on Iterator.

There can be multiple scenarios for java.util.NoSuchElementException. Let’s understand each with the help of examples.


Scenario 1: In case of Enumeration

In Enumeration, if we call the method nextElement() and there is no element present in enumeration then this exception is raised, refer the code below.
Syntax :

Output:

Exception in thread “main” java.util.NoSuchElementException
at java.util.Collections$EmptyEnumeration.nextElement(Collections.j ava:4270)
at Main.main(Main.java:7)

Solution

By using a condition to check if it really have elements by calling method hasMoreElements().
Code:

Above program will run perfectly fine with no exceptions.


Scenario 2: In case of Iterator

In iterator, if we call the method next() and there is no element present in iterator then this exception is raised, refer the code below.

Output:

Exception in thread “main” java.util.NoSuchElementException at
java.util.HashMap$HashIterator.nextNode(HashMap.java:1447) at java.util.HashMap$KeyIterator.next(HashMap.java:1469)
at Main.main(Main.java:6)

Solution

By implementing a condition to check if there is any next element by calling method hasNext().
Code:

Now, this runs without throwing the given Exception.


Scenario 3: In case of StringTokenizer

In StringTokenizer, if we call the method nextElement() or nextToken() and there is no element or token present then this exception is raised, refer the code below.

Output:

Exception in thread “main” java.util.NoSuchElementException
at java.util.StringTokenizer.nextToken (StringTokenizer.java:349)
at Main.main (Main.java:5)

Solution

By using Stringtokenizer’s hasMoreTokens() or hashMoreElements() before proceding to call nextToken() or nextElement().
Code:

Above program will run perfectly fine with no exceptions.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *