How To Fix Exception in Thread “Main” java.util.NoSuchElementException

Exception in Thread “Main” Java.util.nosuchelementexception

Many Java classes allow you to store objects in advanced ways. However, you may run into the Exception in Thread “Main” java.util.NoSuchElementException error when accessing them without care.

Keep reading to find out why the error happens and how you can prevent it.

Exception in Thread “Main” java.util.NoSuchElementException

Reproduce The Error

The java.util.NoSuchElementException error happens a lot when collections are used in Java. In particular, these two examples show how you may run into it when using StringTokenizer and Vector objects.

Example 1

import java.util.StringTokenizer;
public class NoSuchElementException {
    public static void example1() {
        String str = "Welcome to our website";
        StringTokenizer tokens = new StringTokenizer(str, " ");
        
        for(int i = 1; i < 6; ++i) {
            System.out.println(tokens.nextToken());
        }
    }
    public static void main(String[] args) {
        example1();
    }
}

In this example, we use the StringTokenizer class to split a string into tokens – one of the most popular applications of this class. However, after successfully printing out all the substrings, Java displays the error message related to java.util.NoSuchElementException.

Output

Welcome
to
our
website
Exception in thread "main" java.util.NoSuchElementException
	at java.base/java.util.StringTokenizer.nextToken(StringTokenizer.java:349)
	at NoSuchElementException.example1(NoSuchElementException.java:8)
	at NoSuchElementException.main(NoSuchElementException.java:12)

In this example, we use Vector and Enumeration to access elements of a vector in Java.

Example 2

import java.util.Vector;
import java.util.Enumeration;
public class NoSuchElementException {
    public static void example2() {
        Vector<String> str = new Vector<>();
        str.add("Welcome");
        str.add("to");
        str.add("our");
        str.add("website");
        Enumeration<String> e = str.elements();
        for(int i = 1; i < 6; ++i) {
            System.out.println(e.nextElement());
        }
    }
    public static void main(String[] args) {
        example2();
    }
}

As with the first example, this program also shows the java.util.NoSuchElementException error message after printing every element of our vector.

Output

Welcome
to
our
website
Exception in thread "main" java.util.NoSuchElementException: Vector Enumeration
	at java.base/java.util.Vector$1.nextElement(Vector.java:344)
	at NoSuchElementException.example2(NoSuchElementException.java:27)
	at NoSuchElementException.main(NoSuchElementException.java:32)

java.util.NoSuchElementException

NoSuchElementException is a subclass of RuntimeException. Many accessor methods throw this exception when they want to tell you that the element you request doesn’t exist.

Common methods that produce this error are StringTokenizer.nextToken(), Enumeration.nextElement(), and Iterator.next().

In the first example, we use a for loop to control how many times the program should invoke the StringTokenizer.nextToken().

Particularly, the loop calls it five times, while the StringTokenizer instance only has four elements. That is why for the fifth time, Java prints out NoSuchElementException since there are no more elements for the StringTokenizer.nextToken() method to access.

The same thing happens to the second example with the Enumeration interface. Our string provides it with only four elements, but the for loop also calls the nextElement() five times. As a result, we also get the NoSuchElementException error.

This is a runtime exception, meaning the compiler won’t be able to detect any problems with your code. It is not until you run it with the Java Virtual Machine, that this exception will display.

Keep in mind that, like other exceptions in the superclass RuntimeException, there is no need to declare NoSuchElementException in your constructor or method’s throws clause. That is why these exceptions are called ‘unchecked’.

How To Fix The Error

Instead of using the for loop, you can use StringTokenizer.hasMoreTokens() and Enumeration.hasMoreElements() methods.

Example 1

while (tokens.hasMoreTokens()) {
    System.out.println(tokens.nextToken());
}

Example 2

for (Enumeration<String> e = str.elements(); e.hasMoreElements();)
    System.out.println(e.nextElement());

These methods check whether the StringTokenizer and Enumeration have more elements that you can access.

Summary

The Exception in Thread “Main” java.util.NoSuchElementException error occurs when you access elements that don’t exist. You should perform a check to avoid this problem.

Maybe you are interested:

Leave a Reply

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