Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
How to Fix java.util.NoSuchElementException in Java?
Next article icon

How to Fix java.util.NoSuchElementException in Java?

Last Updated : 02 Jun, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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
// Java program to demonstrate the occurrence of // NoSuchElementException  // import required packages import java.io.*; import java.lang.*; import java.util.*;  // driver class class Geek {        // main method     public static void main(String[] args)     {         // creating an hashmap object         HashMap<Integer, Integer> map = new HashMap<>();                // creating an iterator         Iterator itr = map.keySet().iterator();                // trying to access the element         itr.next();     } } 

 
 Output:

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

Java
// Java program to demonstrate the occurrence of // NoSuchElementException  // import required packages  import java.io.*; import java.lang.*; import java.util.*;  // driver class class Geek {        // main method     public static void main(String[] args)     {         // creating an vector object         Vector<Integer> v = new Vector<>();                // creating an enumerator         Enumeration enumerator = v.elements();                // trying to access the element         enumerator.nextElement();     } } 

 Output:

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
// Java program to remove the occurrence of // NoSuchElementException by using hasNext()  // import required packages import java.io.*; import java.lang.*; import java.util.*;  // driver class class Geek {        // main method     public static void main(String[] args)     {         // creating an hashmap object         HashMap<Integer, Integer> map = new HashMap<>();                // creating an iterator         Iterator itr = map.keySet().iterator();                // checking the map object using .hasNext()         // method if it has elements to access         // or not before accessing the map using         // .next() method         while (itr.hasNext())             System.out.println(itr.next());     } } 

Output:

 Example 2:

Java
// Java program to remove the occurrence of // NoSuchElementException by using hasMoreElements()  // import required packages import java.io.*; import java.lang.*; import java.util.*;  // driver class class Geek {        // main method     public static void main(String[] args)     {         // creating an vector object         Vector<Integer> v = new Vector<>();                // creating an enumerator         Enumeration enumerator = v.elements();                // Checking the vector object using         // hasMorelements method if it has elements         // to access or not before accessing the vector         // using .nextElement() method         while (enumerator.hasMoreElements())             System.out.println(enumerator.nextElement());     } } 

Output:


Next Article
How to Fix java.util.NoSuchElementException in Java?

M

mroshanmishra0072
Improve
Article Tags :
  • Java
  • Technical Scripter
  • Technical Scripter 2020
  • Java-Exceptions
Practice Tags :
  • Java

Similar Reads

    How to Solve java.lang.NoSuchMethodError in Java?
    A java.lang.NoSuchMethodError as the name suggests, is a runtime error in Java which occurs when a method is called that exists at compile-time, but does not exist at runtime. The java.lang.NoSuchMethodError can occur in case application code is partially compiled, or in case an external dependency
    3 min read
    How to Fix java.io.StreamCorruptedException: invalid type code in Java?
    There are several problems been faced which are as follows: When you write an object in a file using serialization in java for the first time, no problem arises in reading the file afterward, even when you write multiple objects in one go.Now, when next time you try to append new objects (of the sam
    6 min read
    Fix "java.lang.NullPointerException" in Android Studio
    Hey Geeks, today we will see what NullPointerException means and how we can fix it in Android Studio. To understand NullPointerException, we have to understand the meaning of Null. What is null? "null" is a very familiar keyword among all the programmers out there. It is basically a Literal for Refe
    4 min read
    How to Fix java.lang.UnsupportedClassVersionError in Java?
    The UnsupportedClassVersionError is a sub-class of the LinkageError and thrown by the Java Virtual Machine (JVM). When a class file is read and when major and minor version numbers are not supported, this error is thrown, and especially during the linking phase, this error is thrown A sample snapsho
    3 min read
    How to avoid NullPointerException in Java using Optional class?
    In order to learn how to avoid an error, we must first understand the error. NullPointerException NullPointerException is a RuntimeException. In Java, a special null value can be assigned to an object reference. NullPointerException is thrown when program attempts to use an object reference that has
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences