Java NoSuchElementException


Java NoSuchElementException

Java NoSuchElementException is raised when the element called does not exist in DS.

It is an unchecked exception from java.util package. Following is the hierarchy.

Object –> Throwable –> Exception –> RuntimeException –> NoSuchElementException

Program on Java NoSuchElementException
import java.util.Vector;
public class NSE
{
  public static void main(String args[]) 
  {  
    Vector vect = new Vector();
    System.out.println(vect.firstElement());
  }
}

Java NoSuchElementException

In the above program, Vector object vect is created. No elements are added. Still, it is tried to get the first element. Runtime environment throws Java NoSuchElementException. Observe the screenshot.

Following is another case where NoSuchElementException is thrown. Here, Vector object is created. No elements are added. Enumeration tries to print. JVM throws NoSuchElementException.

import java.util.*;
public class Demo
{
  public static void main(String args[])
  {
    Vector vect = new Vector();
    Enumeration e = vect.elements();
    System.out.println(e.nextElement());
  }
}  

Java NoSuchElementException

In the above code, Vector object vect does not contain elements. The Enumeration object e does not have elements. Calling nextElement() on an empty Enumeration object throws NoSuchElementException.

In Vector programs we know the elements() method returns an object of Enumeration. Enumeration comes with two methods hasMoreElements() and nextElement(). They return boolean value and object respectively.

Leave a Comment

Your email address will not be published.