NoSuchElementException in Java

The NoSuchElementException is thrown by an Enumeration's nextElement method which indicates that there are no more elements left in the enumeration. The NoSuchElementException is thrown by the following methods-

  • nextElement() of Enumeration interface
  • next() of NamingEnumeration interface
  • nextElement() of StringTokenizer class
  • next() of Iterator interface

The NoSuchElementException is a subclass of RuntimeException and implements the Serializable interface.

Constructors of NoSuchElementException

ConstructorDescription
NoSuchElementException()It constructs a NoSuchElementException without any error message as its string.
NoSuchElementException(String s)It constructs a NoSuchElementException, which has a message string s saved which is the reference to the error for later retrieval by the getMessage method. The string s contains the class name which throws the error.

Example of NoSuchElementException

Output:

NoSuchElementException in Java

How to avoid NoSuchElementException?

One of the most common scenarios where the NoSuchElementException occurs is when we are iterating over an empty Set. If we wish to avoid this exception, we can put a check before iterating over the set. While iterating, check every time that there is an element present in the set afterward as follows-

This way ensures that any element is being accessed if it exists.


Next TopicJava Tutorial