Tuesday, November 19, 2024
Google search engine
HomeLanguagesJavaHow to Fix java.util.NoSuchElementException in Java?

How to Fix java.util.NoSuchElementException in Java?

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:

RELATED ARTICLES

Most Popular

Recent Comments