- How to Fix java.util.NoSuchElementException in Java?
- How to Fix the No Such Element Exception in Java
- What Causes NoSuchElementException
- NoSuchElementException Example
- How to Fix NoSuchElementException
- Track, Analyze and Manage Errors With Rollbar
- Related Resources
- No Such Element Exception While Using Scanner in Java
- No Such Element Exception While Using Scanner in Java
- Related Article — Java Error
How to Fix java.util.NoSuchElementException in Java?
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.
How to Fix the No Such Element Exception in Java
The NoSuchElementException is an unchecked exception in Java that can be thrown by various accessor methods to indicate that the element being requested does not exist.
Since the NoSuchElementException is thrown at runtime, it does not need to be declared in the throws clause of a method or constructor.
What Causes NoSuchElementException
The NoSuchElementException can be thrown by various classes or interfaces in Java such as Iterator , Enumerator , Scanner or StringTokenizer .
If an element is requested using the accessor methods of these classes or interfaces, and the underlying data structure does not contain the element, the NoSuchElementException is thrown.
This can occur if the data structure is empty or if its next element is requested after reaching the end of the structure.
NoSuchElementException Example
Here is an example of a NoSuchElementException thrown when trying to access an element of an empty ArrayList using an accessor method of the Iterator interface:
public class NoSuchElementExceptionExample < public static void main(String args[]) < Listlist = new ArrayList(); Iterator it = list.iterator(); System.out.println(it.next()); > >
In the above example, an element of the ArrayList list is requested using the Iterator.next() accessor method. However, since list is empty, the element requested does not exist and the operation throws a NoSuchElementException:
Exception in thread "main" java.util.NoSuchElementException at java.base/java.util.ArrayList$Itr.next(ArrayList.java:970) at NoSuchElementExceptionExample.main(NoSuchElementExceptionExample.java:9)
How to Fix NoSuchElementException
To fix the NoSuchElementException , it should be ensured that the underlying object contains more elements before using accessor methods that can throw the exception. The classes or interfaces that contain these accessor methods usually have a corresponding method to check whether the object contains more elements or not.
For example, the Iterator interface contains the hasNext() method, which should be called before calling Iterator.next() to ensure that the underlying object contains more elements. The Iterator.next() method should only be called if Iterator.hasNext() returns true .
In the earlier example, the exception can be resolved by implementing the above:
public class NoSuchElementExceptionExample < public static void main(String args[]) < Listlist = new ArrayList(); Iterator it = list.iterator(); while (it.hasNext()) < System.out.println(it.next()); > System.out.println("Continuing execution. "); > >
Running the above code produces the correct output as expected:
Track, Analyze and Manage Errors With Rollbar
Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Java errors easier than ever. Sign Up Today!
Related Resources
Can Constructors Throw Exceptions in Java
Handling the ClassCastException Runtime Exception in Java
«Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind.»
No Such Element Exception While Using Scanner in Java
This tutorial will demonstrate solving the NoSuchElementException error while using the Scanner in Java.
No Such Element Exception While Using Scanner in Java
The Scanner class is used to get the user input in a Java program. It uses several utility methods like next() , nextInt() , etc.
When working with these methods, the Scanner can throw a NoSuchElementException error in Java. The reason for these exceptions are given below:
Suppose we have two Scanner objects for getting user input; if we close one Scanner and get the input from the other one, it will throw the NoSuchElementExcpetion . This is because when we close one Scanner, it will close the Input Stream; that is why the other Scanner cannot read from the same Input Stream because the close() method also closes the System.in input stream.
package delftstack; import java.util.*; public class Example public static void main(String args[]) String DemoString = "Hello, This is delftstack.com"; Scanner DemoScanner1 = new Scanner(System.in); Scanner DemoScanner2 = new Scanner(System.in); DemoScanner1.close(); DemoScanner2.next(); > >
The code above will throw the NoSuchElementException . See output:
Exception in thread "main" java.util.NoSuchElementException at java.base/java.util.Scanner.throwFor(Scanner.java:937) at java.base/java.util.Scanner.next(Scanner.java:1478) at delftstack.Example.main(Example.java:13)
To solve this issue, we can use just one Scanner. This also applies if one Scanner is used in one method and the other in another method.
The close() method will close all the input streams.
While using Scanner, we are reading the line, and if there is no line left to read, it will throw the NoSuchElementException . See example:
package delftstack; import java.util.*; public class Example public static void main(String args[]) String DemoString = "Hello, This is delftstack.com"; Scanner DemoScanner1 = new Scanner(DemoString); System.out.println(DemoScanner1.nextLine()); System.out.println(DemoScanner1.nextLine()); > >
To solve the issue, we use the hasNextLine() to check if the Scanner has the next line. It returns true if the Scanner has the next line; otherwise, it returns false.
package delftstack; import java.util.*; public class Example public static void main(String args[]) String DemoString = "Hello, This is delftstack.com"; Scanner DemoScanner1 = new Scanner(DemoString); while(DemoScanner1.hasNextLine()) System.out.println(DemoScanner1.nextLine()); > > >
The output for this code is:
Hello, This is delftstack.com
Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.