Java NoSuchElementException

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

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.

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 Reply

Your email address will not be published. Required fields are marked *