Exception in thread main java util NoSuchElementException

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

import java.io.*;

import java.lang.*;

import java.util.*;

class Geek {

    public static void main(String[] args)

    {

        HashMap map = new HashMap<>();

        Iterator itr = map.keySet().iterator();

        itr.next();

    }

}

Exception in thread main java util NoSuchElementException

Example 2: Here we are trying to access the element of an empty vector object through an enumerator.

Java

import java.io.*;

import java.lang.*;

import java.util.*;

class Geek {

    public static void main(String[] args)

    {

        Vector v = new Vector<>();

        Enumeration enumerator = v.elements();

        enumerator.nextElement();

    }

}

Exception in thread main java util NoSuchElementException

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

import java.io.*;

import java.lang.*;

import java.util.*;

class Geek {

    public static void main(String[] args)

    {

        HashMap map = new HashMap<>();

        Iterator itr = map.keySet().iterator();

        while (itr.hasNext())

            System.out.println(itr.next());

    }

}

Output:

Exception in thread main java util NoSuchElementException

 Example 2:

Java

import java.io.*;

import java.lang.*;

import java.util.*;

class Geek {

    public static void main(String[] args)

    {

        Vector v = new Vector<>();

        Enumeration enumerator = v.elements();

        while (enumerator.hasMoreElements())

            System.out.println(enumerator.nextElement());

    }

}

Output:

Exception in thread main java util NoSuchElementException


Is NoSuchElementException a runtime exception?

It is be cause NoSuchElementException is unchecked exception, which means that it "is-a" RuntimeException which does not force you to catch. The unchecked exceptions classes are the class RuntimeException and its subclasses, and the class Error and its subclasses.

How to implement scanner in Java?

Example 1.
import java.util.*;.
public class ScannerExample {.
public static void main(String args[]){.
Scanner in = new Scanner(System.in);.
System.out.print("Enter your name: ");.
String name = in.nextLine();.
System.out.println("Name is: " + name);.
in.close();.

How to create a scanner object in Java?

Create a Scanner Object in Java Once we import the package, here is how we can create Scanner objects. // read input from the input stream Scanner sc1 = new Scanner(InputStream input); // read input from files Scanner sc2 = new Scanner(File file); // read input from a string Scanner sc3 = new Scanner(String str);