NoSuchElementException

Accomplish Learning NoSuchElementException in Quick 30 Minutes

Table of Contents

Share and Enjoy !

Introduction to Class NoSuchElementException in Java

NoSuchElementException is thrown by mostly the nextElement() method of an enumeration to indicate that there are no more elements in the Enumeration (such as vector) or the stack is empty.

In short, a NoSuchElementException is thrown by Enumeration objects when there are no more elements to be returned. NoSuchElementException implements the serializable interface.

NoSuchElementException is a Runtime Exception. As NoSuchElementException is Runtime exception category, it can only be thrown by JVM(Java virtual machine) during the program execution.

NoSuchElementException is an unchecked exception so we can not declare in the method’s or constructor’s throwable clause.

NoSuchElementException exception is thrown by the below classes:

  • Iterator
  • Enumerator
  • Scanner
  • StringTokenizer

In other words, NoSuchElementException is thrown by the below:

  • nextElement() method of Enumeration interface/StringTokenizer class
  • next() method of NamingEnumeration interface/Iterator interface

All these classes use a data structure and we try to fetch the next element or previous element to get the required data. If the data structure does not have the data anymore and we try to operate next() or nextElement() we get the NoSuchElementException.

Lest see how NoSuchElementException comes?

Mostly NoSuchElementException exception comes if coder misses checking if the underlying data structure (like hashmap) has any more data in it or not.

NoSuchElementException in Hashtable

Operating nextElement() method on Enumeration also produces NoSuchElementException if there is no data present in the Enumeration.

public class TestNoSuchElementException{
public static void main(String args[]){
Hashtable myMap=new Hashtable();
Enumeration enu=myMap.elements();
enu.nextElement();
}
}

The output is java.util.NoSuchElementException
This is because the Hashtable is empty or does not have any more content to show.

NoSuchElementException in HashMap

public class TestNoSuchElementException{
public static void main(String args[]){
HashMap myMap=new HashMap();
Iterator itr=myMap.keySet().iterator();
itr.next();
}
}

The output is java.util.NoSuchElementException
This is because the HashMap is empty or does not have any more content to show.

NoSuchElementException in StringTokenizer

Similarly java.util.StringTokenizer throws NoSuchElementException if the StringTokenizer does not have any more tokens or elements while calling nextToken() or nextElement().

public class TestNoSuchElementException{
public static void main(String args[]){
StringTokenizer myTokens=new StringTokenizer("","->");
System.out.println(myToken.nextToken());
}
}

The output is java.util.NoSuchElementException
This is because the StringTokenizer is empty or does not have any more content to show.

NoSuchElementException in min() method of Collection

min(Collection<?extends T>coll), this min() method of Collection class(java.util.Collections) return the minimum element present in a given collection as per natural ordering of the elements.

The elements in a collection should implement Comparable Interface. That is all elements in the collection are mutually comparable(m1.compareTo(m2)) and they should not throw a ClassCastException for the elements, m1,m2….mn.

public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T>coll)

In this case, if the collection is empty, this min() method throws a NoSuchElementException.
Example

List myList=new LinkedList();
System.out.println("List: "+myList);
int min=Collections.min(myList);

The output of the code:
[]
java.util.NoSuchElementException

NoSuchElementException in Scanner class


class TestScanner{
public static void main(String args[]){
Scanner myScanner=new Scanner(System.in);
int a=myScanner.nextInt();
while(a>0){
int b=myScanner.nextInt();
int[] arrC=new int[b];
int countD=0;
for(int j=0;j<b;j++)
{
arrC[j]=myScanner.nextInt();
}
for(int k=0;k<b-1;k++)
{
for(int l=0;l<b;l++)
{
if(arrC[k]<arr[l])
{
countD=1;
}
}
if(countD==0){
System.out.println(arr[K]+ "");
}
}
}
}

The output is NoSuchElementException

Another example of Scanner class that gives the output as NoSuchElementException


class TestScanner{
public static void main(String args[]){
int x,y;
Scanner myScanner=new Scanner(System.in);
x=myScanner.nextInt();
y=myScanner.nextInt();
int sum=0;
sum=x+y
}

In case, we provide wrong input for x,y, NoSuchElementException will come.

The hierarchy of NoSuchElementException

java.lang.Object
——-java.lang.Throwable
——— java.lang.Exception
————-java.lang.RuntimeException
—————–java.util.NoSuchElementException

The structure of the NoSuchElementException class is given by

public class java.util.NoSuchElementException extends  java.lang.RuntimeException{
//constructors
public NoSuchElementException();
//default constructor and constructs a NoSuchElementException with no details message.
public NoSuchElementException(String message);
//constructs a NoSuchElementException with the message passed in the argument
}

The class NoSuchElementException also inherits methods from class Object and Throwable.

The direct subclass of NoSuchElementException is InputMismatchException

 

From Object classFrom Throwable class
clone()fillInStackTrace()
getClass()getMessage()
notify()printStackTrace()
wait()printStackTrace(PrintWriter)
wait(long, int)getLocalizedMessage()
wait(long)printStackTrace(PrintStream)
equals(Object)toString()
finalize()addSuppressed()
hashCode()getCause()
notifyAll()getLocalizedMessage()
getStackTrace()
getSuppressed()
initcause()
setStackTrace()

How to resolve NoSuchElementException in Java?

It is always a best practice to use hasNext() method before calling next() method on an Iterator and in the context of Enumeration, hasMoreElements() before calling nextElement().

In the context of StringTokenizer, we need to call the below methods before calling nextToken() or nextElement() method.

  • hasMoreTokens()
  • hasMoreElements()

How to resolve NoSuchElementException in StringTokenizer?


public class TestNoSuchElementException{
public static void main(String args[]){
StringTokenizer myTokens=new StringTokenizer("","->");
while(myToken.hasMoreTokens()){
System.out.println(myToken.nextToken());
}
}
}

If hasNext() method throws NoSuchElementException then possibly, we are operating next() method on the elements and we are using next() method more than the number of existing elements in a loop.

How to resolve NoSuchElementException an Iterator?

In the case of Iterator hasNext() method safeguards against NoSuchElementException. Iterator classes have Next() method returns a boolean(true, false) to indicate if the iteration is having any more elements.

Incase, hasNext() returns true, then, the next() method returns the next element in the same iteration.

public class TestNoSuchElementException{
public static void main(String args[]){
Set mySet=new HashSet(15);
Iterator itr=mySet.iterator();
while(itr.hasNext())
itr.next();
}
}

How to resolve NoSuchElementException in HashTable- Enumeration?

In the case of Enumeration hasMoreElement() method safeguards against NoSuchElementException.

public class TestNoSuchElementException{
public static void main(String args[]){
Hashtable myTable=new Hashtable(15);
Enumeration enu=myTable.elements();
while(enu.hasMoreElements()){
enu.nextElement();
}
}
}

Can we use do loop instead of while loop?

While loop is the safest option that is one loop fits in all requirements. But we can use do-while(loop) if we are sure that there is at least one element present in the iteration.


do{
//code
}while(iteration.hasNext())

Role of the classic try-catch block in NoSuchElementException

We can always use a classic try-catch block


while(condition){
try{
//code
iteration.next();
}
catch(NoSuchElementException e)
{
System.out.println(e.getMessage())
}
}
}

How to resolve NoSuchElementException in Scanner class?

Scanner class works differently. So we need to pay attention while working with Scanner class. The java.NoSuchElementException comes in the Scanner context when we call nextLine() method but there is no next line at all.

if(myScanner.hasNextLine()){
String myValue=myScanner.nextLine();
}

This technique eventually covers off a null next line.
When we take input of String just after taking an integer, like-

int x=myScanner.nextInt();
String y=myScanner.nextLine();

This sort of coding also triggers NoSuchElementException. As when we put enter just after putting a number ‘/n’ character gets stored in the buffer as a String. To absorb this extra ‘/n’ character, we need to put an extra nextLine() method in between taking two inputs. Like

int x=myScanner.nextInt();
mScanner.nextLine();
String y=myScanner.nextLine();

How to resolve NoSuchElementException in SAS Management Software?

We may get a java.util.NoSuchElementException while working on SAS Management console and operating on package wizard.

This is a common and known issue of the SAS Management software. This issue occurs if the decision campaign is having references to the data grid identifier. These identifiers exist in the system and do not match with the new campaign that is now imported.

So-net on the net, the preexisting identifier is having more data grid columns than the original campaign.

To avoid this exception, we need to make sure that if we change the data dried identifier, we also need to update all campaigns in the source environment which refer to this data grid identifiers.

In this way, all versions of the identifiers are updated. However, there is a quick fix available. Just navigate to Hot Fix tab then check for the corresponding product family, product, System, Product Release version and SAS release version and download the correct fix for your need.

How to resolve NoSuchElementException in Kotlin, Spart, Firebase and Android Studio?

90% of the cases, we get NoSuchElementException while trying to obtain information from an empty list without checking if the list has more elements in it.

How to resolve NoSuchElementException in jbo.server?

Oracle.jbo.server.java.util.NoSuchElementException can also throw the exception in the same context.

The hierarchy of NoSuchElementException in jbo.server

java.lang.Object
——-java.lang.Throwable
——— java.lang.Exception
————-java.lang.RuntimeException
—————–java.jbo.server.java.util.NoSuchElementException

NoSuchElementException in Selenium

NoSuchElementException can also be thrown by Selenium java or org.openqa.selenium by the following codes:

  • WebDriver.findElement(By by);
  • WebElement.findElement(By by);

NoSuchElementException is selenium can occur due to several reasons:

  • The page may not have been loaded correctly that is it is still being rendered as a result the findElement() method using a By strategy is failing. This happens due to the speed mismatch of the Selenium and webpage. By the time the page is loaded along with the components, the search operation is already finished.
  • The element may not be visible in the active window.
  • The element is taking time to get loaded in the page. We need to wait for the element.
  • The element is really not there. Application is updated but not the script.
  • If the page is written in AJAX, the AJAX has not returned the necessary element.
  • For legacy application, the element can be visible and present but still, Selenium can throw this exception.
  • Screenshot capturing using TakesScreenshot() method can also throw this exception.
  • The locator by which we are trying to find the element may have changed.

The hierarchy of NoSuchElementException in Selenium

java.lang.Object
——-java.lang.Throwable
——— java.lang.Exception
————-java.lang.RuntimeException
—————–org.openqa.selenium.WebDriverException
———————-org.openqa.selenium.NotFoundException
————————–org.openqa.selenium.NoSuchElementException

The direct subclass in the java selenium context is InvalidSelectorException

The constructors for this class are as follows

  • NoSuchElementException(String reason)
  • NoSuchElementException(String reason,Throwable cause)

Apart from regular NoSuchElementException in java, this class in Selenium context provides one more method. That is as follows:

public String getSupportURL()

getSupportURL() method overrides getSupportURL() method of WebDriverException class.

Methods inherited from class org.openqa.selenium.WebDriverException is as follows:

  • addInfo()
  • getAdditionalInformation()
  • getDriverName()
  • getBuildInformation()
  • getMessage()
  • getSystemInformation()

How to resolve NoSuchElementException in Page loading issue?

In this case, we can use the wait strategy to wait for loading the page correctly. The popular wait syntax:

driver.manage().timeouts().pageLoadTimeout(45,TimeUnit.SECONDS);

How to resolve NoSuchElementException in Element not visible issue?

A scroll down/up request is required in order to make the element visible properly. We can use JavascriptExecutor to scroll down or up. The syntax is given as:

JavascripptExecutor js=(JavascriptExecutor)driver;
js.executeScript("window.scrollBy(0,200)","");

How to resolve NoSuchElementException in Element loading issue?

As we need to wait for the component or element, we can use one of the below strategies

WebDriver wait until
WebDriverWait myWait=new WebDriverWait(driver,delay);
myWait.until(ExpectedConditions.visibilityOf(element));

or

WebDriverWait myWait=new WebDriverWait(driver,delay);
myWait.until(ExpectedConditions.visibilityOfElementLocated(By.by(elementLocatorStrategy));
Java’s Classic Thread.sleep()- hardcoded wait
Thread.sleep(2000);
Fluent wait

FluentWait can be another good option for waiting for an element. Below syntax waits for 45 seconds for an element to appear on the page and checks every 5 seconds for its presence.

Wait<WebDriver> myWait=new FluentWait<WebDriver>(driver)
.withTimeout(45,SECONDS)
.pollingEvery(5,SECONDS)
.ignoring(NoSuchElementException.class);

WebElement myElement=myWait.until(new Function<WebDriver,WebElement>(){
public WebElement apply(WebDriver driver){
return driver.findElement(By.id("xyz"));
}
});

Commonly used fluent wait methods.

withTimeout

public FluentWait withTimeout(long duration, java.util.concurrent.TimeUnit unit)

Parameters:
duration – The timeout duration.
unit – The unit of time.
Returns:
A self-reference. The above method sets the wait for the condition to become true. The default timeout is FIVE_HUNDRED_MILLIS.

withMessage

public FluentWait withMessage(java.lang.String message)

Parameters:
message – to be appended to default.
Returns:
A self-reference. The above method sets the message which would appear after the timeout.

pollingEvery

public FluentWait pollingEvery(long duration, java.util.concurrent.TimeUnit unit)

Parameters:
duration – The timeout duration.
unit – The unit of time.
Returns:
A self-reference. This method sets the frequency of condition should be evaluated. The default polling interval is FIVE_HUNDRED_MILLIS.

ignoring

public FluentWait ignoring(java.lang.Class<? extends java.lang.Throwable> firstType, java.lang.Class<? extends java.lang.Throwable> secondType)

Parameters:
firstType – exception to ignore.
secondType – another exception to ignore.
Returns:
a self-reference. This method lists the exception that you want to skip when the timeouts.

Advanced fluent wait methods.

until

public void until(com.google.common.base.Predicate isTrue)

Parameters:
isTrue – The predicate to wait on.
Throws:
TimeoutException – If the timeout expires.
It’ll apply the instance’s input value to the given predicate until the timeout occurs or the predicate becomes true.

until

publicV until(com.google.common.base.Function<? super T,V> isTrue)

Specified by:
until in interface Wait
Type Parameters:
V – The function expected return type.
Parameters:
isTrue – the parameter to pass to the ExpectedCondition.
Returns:
The functions return value if the function returned something different from null or false before the timeout expired.
Throws:
TimeoutException- If the timeout expires.

It will apply the instance’s input value to the given function until one of the following conditions occurs:

  • The function returns neither null nor false.
  • The function throws an un-ignorable exception.
  • The timeout expires.
  • The current thread gets interrupted.

timeoutException

protected java.lang.RuntimeException timeoutException(java.lang.String message, java.lang.Throwable lastException)

Parameters:
message – The timeout message.
lastException – The last exception to be thrown and subsequently suppressed while waiting on a function.
Returns: Nothing will ever be returned; this return type is only specified as a convenience.
This method throws a timeout exception.

How to resolve NoSuchElementException for legacy application where the element is still present and visible?

Generally, in legacy web application this scenario is very common. During the old days of development, the DOM was not properly constructed. So it may so happen that the element is completely detached from the DOM. (Document Object Model).

Or the legacy app may have been updated recently. We may miss that. Hence we are giving the wrong ID, name, link text, CSSSelector and Xpath.

Stale Element-

Stale element happens when the element was deleted or not available or not attached to the DOM anymore.

We can cross-check all these along with we can try providing the absolute Xptah instead of relative XPath.

How to resolve NoSuchElementException in TakesScreenshot?

While working with Selenium’s TakesScreenshot, the method getScreenshotAs() can throw NoSuchElementException due to the fact that the given element is not within the form. We may have missed using switchTo(form_id) method.

While working with Selenium’s findElement/findElements(By by) to find an element or a list of elements, java.util.List<WebElement> findElements(By by) throws NoSuchElementException if the By strategy can not find the element specified.

How to resolve NoSuchElementException on the import-related issue?

We need to import org.openqa.selenium.NoSuchElementException instead of java.util.NoSuchElementException while working with Selenium java.

How to resolve NoSuchElementException in Framework issue?

Many times when we use some framework in selenium, the framework may store objects in the object repository. During object identification process we often miss putting object identifications(XPath, id, name etc) as String. Like-

logOutButton=//*[text()\='log\Out']

instead of

logOutButton="/*[text()\='log\Out']"

So while retrieving the object from the repository and feeding into the application by using a BY strategy like-

logOutButton=driver.findElement(By.xpath(objRepo.logout));

This exception may come.
Similarly, for some cases, the By strategy may take this differently and not as a String.

Mostly, all these issues can be seen and rectified by using a Screenshot.

Conclusion

NoSuchElementException is thrown when we attempt to access an element that is non-existent. This exception is thrown by Enumeration, Iterator, ListIterator and Selenium when nextElement(), next(), previous() etc methods are called and it goes beyond the end of the list elements.

Vector, Stack class can also throw the same exception where we try to access the first or the last element of an empty collection.

NoSuchElementException may also come if the stream from where we are reading or to where we are writing is already closed.

Interestingly, NoSuchElementException is also thrown when we try to access some element that is not present in the underlying data structure.

In the context of selenium, this exception may come due to page loading issue, or element not found issues.

In all the cases, careful coding can eliminate this exception, as described above.

Share and Enjoy !

Leave a Comment

Your email address will not be published. Required fields are marked *