Ravi
Ravi

Reputation: 53

Unable to catch exception NoSuchElementException

My try block throws NoSuchElementException but my catch block is unable to proceed.

In my automation suite I get a page with btnOk element sometimes(first login everyday) so I am trying to handle the scenario where if the page comes then click on it and proceed otherwise continue any ways.

Code snippet below:

try {
    WebElement submitbuttonPresence=driver.findElement(By.id("btnOk"));
    submitbuttonPresence.click();
}
catch (NoSuchElementException e) {
    System.out.println(driver.getTitle());
}

Upvotes: 4

Views: 8843

Answers (2)

Guy
Guy

Reputation: 50809

There are two NoSuchElementException, one in java.util and one in org.openqa.selenium. To catch WebDriver exceptions you need the second one

import org.openqa.selenium.NoSuchElementException

Upvotes: 5

Buaban
Buaban

Reputation: 5127

It seems you catch an incorrect exception. Try code below:

try {
    WebElement submitbuttonPresence=driver.findElement(By.id("btnOk"));
    submitbuttonPresence.click();
}
catch (org.openqa.selenium.NoSuchElementException e) {
    System.out.println(driver.getTitle());
}

Upvotes: 6

Related Questions