Abdurehman Siddiqui
Abdurehman Siddiqui

Reputation: 81

try catch is not working on isDisplayed() in selenium and throwing s

Element is not present on the page!

here is the code:

try {
        if (driver.findElement(By.xpath("(//*[text()='Duplicate Saved Filter'])")).isDisplayed()) {
   
            driver.findElement(By.xpath("(//*[text()=' Yes '])")).click();
            Thread.sleep(2000);
    }} catch (NoSuchElementException e) {
        logger.info("element not found");
        }

Upvotes: 0

Views: 860

Answers (1)

Taco Verhagen
Taco Verhagen

Reputation: 232

What you want:

  • click on Yes if element is present and visible
  • otherwise log something, without error throwing

The trick here is to use findElementS (notice the S). This gives a list of found elements, if 0 than there is no element (prevents the error throwing). If there is an element, check if it is displayed. From your comment I guess you tried to use findElementS but forgot to add the .size() > 0 check.

List<WebElement> elements = driver.findElements(By.xpath("(//*[text()='Duplicate Saved Filter'])"));
if(elements.size() == 0) {
    logger.info("element not found");
} else if(!elements[0].Displayed())) {
    logger.info("element not visisble");
} else {
    driver.findElement(By.xpath("(//*[text()=' Yes '])")).click();
    Thread.sleep(2000);
}

Upvotes: 1

Related Questions