Fix the NoSuchElementException Error in Java
An exception is an event that happens during a program’s execution. The normal program flow is affected when an exception occurs, and the program terminates abnormally. This tutorial will discuss java.util.NoSuchElementException and how to handle it in Java.
The NoSuchElementException inherits from the RuntimeException class, which means it’s an unchecked Exception. Unchecked Exceptions are not handled by the compiler, as they happen during runtime.
The NoSuchElementException is thrown by Scanner class, Iterator interface, Enumerator interface, and StringTokenizer class. These classes have accessors’ methods to fetch the next element from an iterable. They throw NoSuchElementException if the iterable is empty or has reached the maximum limit.
Let’s look at how different classes throw NoSuchElementException .
NoSuchElementException While Using Iterator in Java
The Iterator interface has a method called next() used to access the next element in the iteration. If no element is in the collection, then NoSuchElementException is thrown. We will look at some examples.
Trying to iterate a HashMap with no elements:
The next() method throws an exception because the HashMap is empty. We can use the hasNext() method to avoid this exception; it returns true if the iterable has more elements.
We should use the next() method only if hasNext() returns True, to avoid such exceptions. See the example below.
This code throws no exception. Let’s take an example with some elements in the HashMap and iterate the elements.
Without the hasNext() method, this code would have thrown an exception, but it’s working fine.
NoSuchElementException While Using Enumeration in Java
In Java, Enumeration has a method called nextElement() that returns the next element of the enumeration. If there’s no element to return, it throws a NoSuchElementException .
Look at the example below where we are creating an enum from a list.
The hasElement() throws an exception after returning the first element because no elements are left in the ArrayList to be accessed. We can use the hasMoreElements() method to avoid this situation.
This method returns true if there are more elements in the enumeration to provide; else, it returns false. We can call the nextElement() method only if there are more elements in the enumeration.
Look at the example below:
NoSuchElementException While Using StringTokenizer in Java
In Java, StringTokenizer class provides two methods, the nextToken() and nextElement() . The nextToken() method returns the next token(string type) from the string tokenizer, whereas the nextElement method is like the nexttoken() except that it returns an object type rather than a string. Both methods throw the NoSuchElementException .
See the example below.
We can avoid the exception using the hasMoreTokens() and hasMoreElements() method. Both methods return true if more tokens are available in the tokenizer’s string. We should call the nextToken() method only if hasMoreTokens() method returns True.
See the example below:
NoSuchElementException While Using Scanner Class in Java
The Scanner class in Java provides several utility methods such as next(), nextInt(), etc. While working with these methods, they can throw the NoSuchElementException . We will discuss them here.
- Suppose you have two scanner objects accessing the Standard Input. If you close one of them and call a method using the other one, it throws the NoSuchElementException . See the example below.
When we close the first Scanner, it closes the underlying InputStream ; therefore, the second Scanner can’t read from the same InputStream and throws a NoSuchElementException . The solution is to use one scanner object to read System.in input.
- Suppose you’re reading a string or a file using the scanner object. If there’s no line left to read, an exception shows. See the example below.
To solve this problem, we use the hasNextLine() method that returns a Boolean value. Look at the example.
Facing Issues On IT
[Solved]java.util.NoSuchElementException
java.util.NoSuchElementException is runtime unchecked exception which throws by nextElement() method of an Enumeration or nextXYZ() method of Scanner to indicate that there are no more elements in the enumeration or scanner.
- SubClass of NoSuchElementException is InputMismatchException
Constructors
- NoSuchElementException() : Constructs a NoSuchElementException with null as its error message string.
- NoSuchElementException(String s) : Constructs a NoSuchElementException, saving a reference to the error message string s for later retrieval by the getMessage() method.
Example NoSuchElementException
In below example NoSuchElementException occured because using useDelimiters(“\sGaurav\s“) while in test input using delimiters as “Saurabh”. In that case scanner will have only one text line and not split. When we retrieve data from scanner will throw this NoSuchElementException.
Output
Solutions
- In case of enumeration always check for hasNextElement() before use method next() to retrieve element of enumeration.
- In case of Scanner always check for hasNext() before use method nextXYZ() to retrieve values from scanner.
References
Know More
To know more about Java Exception Hierarchy, in-built exception , checked exception, unchecked exceptions and solutions. You can learn about Exception Handling in override methods and lots more. You can follow below links: s
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:
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:
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:
Running the above code produces the correct output as expected:
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!