Blog |

How to Fix the No Such Element Exception in Java

How to Fix the No Such Element Exception in Java
Table of Contents

The NoSuchElementException is an unchecked exception in Java that can be thrown by various accessor methods to indicate that the element being requested does not exist.

Since the NoSuchElementException is thrown at runtime, it does not need to be declared in the throws clause of a method or constructor.

 

What Causes NoSuchElementException

The NoSuchElementException can be thrown by various classes or interfaces in Java such as Iterator, Enumerator, Scanner or StringTokenizer.

If an element is requested using the accessor methods of these classes or interfaces, and the underlying data structure does not contain the element, the NoSuchElementException is thrown.

This can occur if the data structure is empty or if its next element is requested after reaching the end of the structure.

 

NoSuchElementException Example

Here is an example of a NoSuchElementException thrown when trying to access an element of an empty ArrayList using an accessor method of the Iterator interface:

public class NoSuchElementExceptionExample {
    public static void main(String args[]) {
        List<Integer> list = new ArrayList<Integer>();
        Iterator<Integer> it = list.iterator();
        System.out.println(it.next());
    }
}

In the above example, an element of the ArrayList list is requested using the Iterator.next() accessor method. However, since list is empty, the element requested does not exist and the operation throws a NoSuchElementException:

Exception in thread "main" java.util.NoSuchElementException
    at java.base/java.util.ArrayList$Itr.next(ArrayList.java:970)
    at NoSuchElementExceptionExample.main(NoSuchElementExceptionExample.java:9)

 

How to Fix NoSuchElementException

To fix the NoSuchElementException, it should be ensured that the underlying object contains more elements before using accessor methods that can throw the exception. The classes or interfaces that contain these accessor methods usually have a corresponding method to check whether the object contains more elements or not.

For example, the Iterator interface contains the hasNext() method, which should be called before calling Iterator.next() to ensure that the underlying object contains more elements. The Iterator.next() method should only be called if Iterator.hasNext() returns true.

In the earlier example, the exception can be resolved by implementing the above:

public class NoSuchElementExceptionExample {
    public static void main(String args[]) {
        List<Integer> list = new ArrayList<Integer>();
        Iterator<Integer> it = list.iterator();

        while (it.hasNext()) {
            System.out.println(it.next());
        }

        System.out.println("Continuing execution...");
    }
}

Running the above code produces the correct output as expected:

Continuing execution...

 

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Java errors easier than ever. Sign Up Today!

Related Resources

"Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind."

Error Monitoring

Start continuously improving your code today.

Get Started Shape