Different scenarios that cause NoSuchElementException in Java.


An exception is an issue (run time error) occurred during the execution of a program. When an exception occurs the program gets terminated abruptly and, the code past the line that generated the exception never gets executed. Each exception is represented by its respective class.

NosuchElement Exception

This is a Runtime exception i.e. it occurs at the execution time.

While accessing the contents of a collection, array or other objects using the accessor methods of an Enumeration, Iterator or, tokenizer, such as next() or nextElement(), if you try to get the elements from an empty object, or if you try to get the next element after reaching the end of the object (collection, array, or other) a NoSuchElementException is generated.

Scenarios

nextElement() method of the Enumeration − The collections like Vector, HashTable etc. has a method named elements() which returns an Enumeration (interface) object containing all the elements in the collection.

Using this object, you can get the elements one by one using the nextElement() method.

If you invoke this method on an empty collection or, after reaching the end of the collection a NosuchElementException will be generated at the run time.

Example

import java.util.Enumeration;
import java.util.Vector;
public class EnumExample {
   public static void main(String args[]) {
      //instantiating a Vector
      Vector<Integer< vec = new Vector<Integer>( );
      //Populating the vector
      vec.add(1254);
      vec.add(4587);
      //Retrieving the elements using the Enumeration
      Enumeration<Integer> en = vec.elements();
      System.out.println(en.nextElement());
      System.out.println(en.nextElement());
      //Retrieving the next element after reaching the end
      System.out.println(en.nextElement());
   }
}

Runtime error

1254
4587
Exception in thread "main" java.util.NoSuchElementException: Vector Enumeration
   at java.util.Vector$1.nextElement(Unknown Source)
   at MyPackage.EnumExample.main(EnumExample.java:18)

nextElement() and nextToken()methods of the StringTokenizer − The StringTokenizer class accepts a String and delimiter as parameters of one of its constructors, splits the given String into several small tokens, every time the given delimiter occurs.

The nextToken() and nextElement() methods of this class returns the next token in the tokenizer. If you invoke these methods on an empty Tokenizer object or, after reaching the end a NoSuchElementException will be generated at the run time.

Example

import java.util.StringTokenizer;
public class StringTokenizerExample{
   public static void main(String args[]) {
      String str = "Hello how are you";
      //Instantiating the StringTokenizer class
      StringTokenizer tokenizer = new StringTokenizer(str, " ");
      //Printing all the tokens
      System.out.println(tokenizer.nextToken());
      System.out.println(tokenizer.nextToken());
      System.out.println(tokenizer.nextToken());
      System.out.println(tokenizer.nextToken());
      //Getting the next token after reaching the end
      tokenizer.nextToken();
      tokenizer.nextElement();
   }
}

Runtime error

Hello
how
are
you
Exception in thread "main" java.util.NoSuchElementException
   at java.util.StringTokenizer.nextToken(Unknown Source)
   at MyPackage.StringTokenizerExample.main(StringTokenizerExample.java:16)

next() method of the Iterator − Java provides Iterator and ListIterator classes to retrieve the elements of the collection object. The next() methods of the Iterator and ListIterator returns the next element of the collection.

If these methods are invoked on the empty collection or, after reaching the end a NoSuchElementException is generated at the runtime.

Similarly, the previous() method of the ListIterator returns the previous element of the collection, if this method is invoked on an empty object or at the stating position of it a NoSuchElementException is generated at the runtime.

Example

import java.util.ArrayList;
import java.util.Iterator;
public class NextElementExample{
   public static void main(String args[]) {
      //Instantiating an ArrayList object
      ArrayList<String> list = new ArrayList<String>();
      //populating the ArrayList
      list.add("apples");
      list.add("mangoes");
      list.add("oranges");
      //Getting the Iterator object of the ArrayList
      Iterator it = list.iterator();
      System.out.println(it.next());
      System.out.println(it.next());
      System.out.println(it.next());
      //Retrieving next element after reaching the end
      it.next();
   }
}

Runtime error

apples
mangoes
oranges
Exception in thread "main" java.util.NoSuchElementException
   at java.util.ArrayList$Itr.next(Unknown Source)
   at MyPackage.NextElementExample.main(NextElementExample.java:19)

Example (previous() method)

import java.util.ArrayList;
import java.util.ListIterator;
public class NextElementExample{
   public static void main(String args[]) {
      //Instantiating an ArrayList object
      ArrayList<String> list = new ArrayList<String>();
      //populating the ArrayList
      list.add("apples");
      list.add("mangoes");
      list.add("oranges");
      //Getting the Iterator object of the ArrayList
      ListIterator<String> it = list.listIterator();
      it.next();
      it.next();
      it.next();
      System.out.println(it.previous());
      System.out.println(it.previous());
      System.out.println(it.previous());
      System.out.println(it.previous());
   }
}

Output

oranges
mangoes
apples
Exception in thread "main" java.util.NoSuchElementException
   at java.util.ArrayList$ListItr.previous(Unknown Source)
   at MyPackage.NextElementExample.main(NextElementExample.java:22)

Updated on: 06-Aug-2019

197 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements