Friday, February 24, 2012

How to fix java.util.NoSuchElementException in Java

java.util.NoSuchElementException is a RuntimeException which can be thrown by different classes in Java like Iterator, Enumerator, Scanner or StringTokenizer. All of those classes has method to fetch next element or next tokens if underlying data-structure doesn't have any element Java throws "java.util.NoSuchElementException". Most common example of this iterating over hashmap without checking if there is any element or not and that's why it's advised to use hashNext() before calling next() on Iterator. In this Java tutorial we will what causes NoSuchElementException in Java and how to avoid it completely.

Cause of Exception in thread "main" java.util.NoSuchElementException:

here are possible cause of java.util.NoSuchElementException in Java:

1) As per Javadoc NoSuchElementException is thrown if you call nextElement() method of Enumeration and there is

no more element in Enumeration. below code will throw java.util.NoSuchElementException because Enumeration of hastable is empty.

In order to avoid these NoSuchElementException always call Iterator.hasNext() or Enumeration.hasMoreElements() before calling next() or nextElement() method.

java.util.StringTokenizer can also throw NoSuchElementException if there is no more token or element and you call

nextToken() or nextElement() method. here is an example of java.util.NoSuchElementException while using StringTokenizer in Java

import java.util.StringTokenizer;

public class StringTokenizerDemo {

public static void main(String args[]) {

StringTokenizer tokenReader = new StringTokenizer("", ":");

System.out.println(tokenReader.nextToken());

}

}

Exception in thread "main" java.util.NoSuchElementException

at java.util.StringTokenizer.nextToken(StringTokenizer.java:332)

at test.ExceptionTest.main(StringTokenizerDemo.java:23)

To get rid of this exception while using Stringtokenizer call hasMoreTokens() or hashMoreElements() before proceding

to call nextToken() or nextElement().

here is modified code which will not throw java.util.NoSuchElementException even if there is no more element because

its safe guarded form hashMoreTokens() method which return true if there is more tokens available.

StringTokenizer tokenReader = new StringTokenizer("", ":");

while (tokenReader.hasMoreTokens()) {

System.out.println(tokenReader.nextToken());

}

We have seen possible cause of java.lang.NoSuchElementException in Java , It can come while using Iterator or Enumeration or StringTokenizer. Best way to fix NoSuchElementException in java is to avoid it by checking Iterator with hashNext(), Enumeration with hashMoreElements() and StringTokenizer with hashMoreTokens().