How to Fix java.util.NoSuchElementException in Java?
Last Updated : 02 Jun, 2023
An unexpected, unwanted event that disturbed the normal flow of a program is called Exception. Most of the time exceptions are caused by our program and these are recoverable. Suppose if our program requirement is to read data from the remote file locating in the U.S.A. At runtime, if a remote file is not available then we will get RuntimeException saying fileNotFoundException. If fileNotFoundException occurs we can provide the local file to the program to read and continue the rest of the program normally.
There are mainly two types of exception in java as follows:
1. Checked Exception: The exception which is checked by the compiler for the smooth execution of the program at runtime is called a checked exception. In our program, if there is a chance of rising checked exceptions then compulsory we should handle that checked exception (either by try-catch or throws keyword) otherwise we will get the compile-time error. Examples of checked exceptions are ClassNotFoundException, IOException, SQLException, etc.
2. Unchecked Exception: The exceptions which are not checked by the compiler, whether programmer handling or not such type of exception are called an unchecked exception. Examples of unchecked Exceptions are ArithmeticException, ArrayStoreException, etc.
Whether the exception is checked or unchecked every exception occurs at run time only if there is no chance of occurring any exception at compile time.
NoSuchElementException:
It is the child class of RuntimeException and hence it is an unchecked exception. This exception is rise automatically by JVM and given by the accessors methods of Enumeration, Iterator or Tokenizer such as next() or nextElement() or nextToken() when we are trying to access the content of an array, collection, or any other object and if these objects are empty or if we are trying to get next element after reaching the end of an object then we will get java.util.NoSuchElementException.
In the below example we are trying to access a HashMap by using the accessor method next() of the Iterator class but as the HashMap is empty we will be going to get NoSuchElementException.
Example 1:
Java // Java program to demonstrate the occurrence of // NoSuchElementException // import required packages import java.io.*; import java.lang.*; import java.util.*; // driver class class Geek { // main method public static void main(String[] args) { // creating an hashmap object HashMap<Integer, Integer> map = new HashMap<>(); // creating an iterator Iterator itr = map.keySet().iterator(); // trying to access the element itr.next(); } }
Output:

Example 2: Here we are trying to access the element of an empty vector object through an enumerator.
Java // Java program to demonstrate the occurrence of // NoSuchElementException // import required packages import java.io.*; import java.lang.*; import java.util.*; // driver class class Geek { // main method public static void main(String[] args) { // creating an vector object Vector<Integer> v = new Vector<>(); // creating an enumerator Enumeration enumerator = v.elements(); // trying to access the element enumerator.nextElement(); } }
Output:

How to solve this error?
Almost all the classes whose accessor methods give NoSuchElementException contains their respective method to check whether the object contains more elements or not. So in order to avoid this NoSuchElementException we need to always call,
- Iterator.hasNext() or
- Enumeration.hasMoreElements() or
- hasMoreToken() method before calling next( ) or nextElement or nextToken() method.
Below is the implementation of the above statement :
Example 1:
Java // Java program to remove the occurrence of // NoSuchElementException by using hasNext() // import required packages import java.io.*; import java.lang.*; import java.util.*; // driver class class Geek { // main method public static void main(String[] args) { // creating an hashmap object HashMap<Integer, Integer> map = new HashMap<>(); // creating an iterator Iterator itr = map.keySet().iterator(); // checking the map object using .hasNext() // method if it has elements to access // or not before accessing the map using // .next() method while (itr.hasNext()) System.out.println(itr.next()); } }
Output:

Example 2:
Java // Java program to remove the occurrence of // NoSuchElementException by using hasMoreElements() // import required packages import java.io.*; import java.lang.*; import java.util.*; // driver class class Geek { // main method public static void main(String[] args) { // creating an vector object Vector<Integer> v = new Vector<>(); // creating an enumerator Enumeration enumerator = v.elements(); // Checking the vector object using // hasMorelements method if it has elements // to access or not before accessing the vector // using .nextElement() method while (enumerator.hasMoreElements()) System.out.println(enumerator.nextElement()); } }
Output:

Similar Reads
How to Solve java.lang.NoSuchMethodError in Java? A java.lang.NoSuchMethodError as the name suggests, is a runtime error in Java which occurs when a method is called that exists at compile-time, but does not exist at runtime. The java.lang.NoSuchMethodError can occur in case application code is partially compiled, or in case an external dependency
3 min read
How to Fix java.io.StreamCorruptedException: invalid type code in Java? There are several problems been faced which are as follows: When you write an object in a file using serialization in java for the first time, no problem arises in reading the file afterward, even when you write multiple objects in one go.Now, when next time you try to append new objects (of the sam
6 min read
Fix "java.lang.NullPointerException" in Android Studio Hey Geeks, today we will see what NullPointerException means and how we can fix it in Android Studio. To understand NullPointerException, we have to understand the meaning of Null. What is null? "null" is a very familiar keyword among all the programmers out there. It is basically a Literal for Refe
4 min read
How to Fix java.lang.UnsupportedClassVersionError in Java? The UnsupportedClassVersionError is a sub-class of the LinkageError and thrown by the Java Virtual Machine (JVM). When a class file is read and when major and minor version numbers are not supported, this error is thrown, and especially during the linking phase, this error is thrown A sample snapsho
3 min read
How to avoid NullPointerException in Java using Optional class? In order to learn how to avoid an error, we must first understand the error. NullPointerException NullPointerException is a RuntimeException. In Java, a special null value can be assigned to an object reference. NullPointerException is thrown when program attempts to use an object reference that has
4 min read