[Solved]java.util.NoSuchElementException


java.util.NoSuchElementException is runtime unchecked exception which throws by  nextElement() method of an Enumeration or nextXYZ() method of Scanner to indicate that there are no more elements in the enumeration or scanner.

Constructors

  • NoSuchElementException() : Constructs a NoSuchElementException with null as its error message string.
  • NoSuchElementException(String s) : Constructs a NoSuchElementException, saving a reference to the error message string s for later retrieval by the getMessage() method.

Example  NoSuchElementException

In below example NoSuchElementException occured because using useDelimiters(“\sGaurav\s“) while in test input using delimiters as “Saurabh”. In that case scanner will have only one text line and not split. When we retrieve data from scanner will throw this NoSuchElementException.

import java.util.Scanner;
public class JavaScannerParsingExample {
	public static void main(String[] args) {
		String input = "Facing Saurabh Issues Saurabh On Saurabh IT Saurabh 123 Saurabh 54 Saurabh";
	     Scanner s = new Scanner(input).useDelimiter("\s*Gaurav\s*");
	     System.out.println(s.next());
	     System.out.println(s.next());
	     System.out.println(s.next());
	     System.out.println(s.next());
	     System.out.println(s.nextInt());
	     System.out.println(s.nextInt());
	     s.close();
	}
}

Output

Facing Saurabh Issues Saurabh On Saurabh IT Saurabh 123 Saurabh 54 Saurabh
Exception in thread "main" java.util.NoSuchElementException
	at java.util.Scanner.throwFor(Unknown Source)
	at java.util.Scanner.next(Unknown Source)
	at com.userinput.JavaScannerParsingExample.main(JavaScannerParsingExample.java:11)

Solutions

  • In case of enumeration always check for hasNextElement() before use method next() to retrieve element of enumeration.
  • In case of Scanner always check for hasNext() before use method nextXYZ() to retrieve values from scanner.

References

https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html

Know More

To know more about Java Exception Hierarchy, in-built exception , checked exception, unchecked exceptions and solutions. You can learn about Exception Handling in override methods and lots more. You can follow below links:  s

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s