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-
The NoSuchElementException is a subclass of RuntimeException and implements the Serializable interface.
| Constructor | Description |
|---|---|
| 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. |
Output:

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.
We request you to subscribe our newsletter for upcoming updates.

We deliver comprehensive tutorials, interview question-answers, MCQs, study materials on leading programming languages and web technologies like Data Science, MEAN/MERN full stack development, Python, Java, C++, C, HTML, React, Angular, PHP and much more to support your learning and career growth.
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India