Home > Mobile >  Java Selenium NoSuchElementException not thrown
Java Selenium NoSuchElementException not thrown

Time:03-08

I am pretty new with java with selenium and got a question regarding the NoSuchElementException:

I got the following method which should return a WebElement:

public WebElement getElementByXpath(String xpath, WebDriver driver) {
    try {
        System.out.println("Test");
        return driver.findElement(By.xpath(xpath));
    } catch (NoSuchElementException e) {
        System.out.println("Element not found");
    }

    return null;
}

So what I want is, that if the Element is not found than only "Element not found" will be printed. But instead of this I get the full Error Message, but no "Element not found":

Test
2022-03-07 16:22:33.159 ERROR 1 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//select[@id='sr_creg_country123']/option[contains(text(), 'Deutschland')]"}
(Session info: chrome=98.0.4758.80)
For documentation on this error, please visit: https://www.seleniumhq.org/exceptions/no_such_element.html
Build info: version: 'unknown', revision: 'unknown', time: 'unknown'
.
. 
.

As I understand it the Exception will not be thrown, because the Message "Element not found" is never printed? But can someone explain me why and what do I have to do that the code in the catch-block will be executed?

Cheers, Michael

CodePudding user response:

There are two NoSuchElementException exceptions in Java, one is in java.util and the other is in org.openqa.selenium. In order to catch WebDriver NoSuchElementException exception you need to define the catch explicitly catch (org.openqa.selenium.NoSuchElementException e) as following:

public WebElement getElementByXpath(String xpath, WebDriver driver) {
    try {
        System.out.println("Test");
        return driver.findElement(By.xpath(xpath));
    } catch (org.openqa.selenium.NoSuchElementException e) {
        System.out.println("Element not found");
    }

    return null;
}

Alternatively you can import the exception you want to use

import org.openqa.selenium.NoSuchElementException

So that your method code can remain without changes:

import org.openqa.selenium.NoSuchElementException

public WebElement getElementByXpath(String xpath, WebDriver driver) {
    try {
        System.out.println("Test");
        return driver.findElement(By.xpath(xpath));
    } catch (NoSuchElementException e) {
        System.out.println("Element not found");
    }

    return null;
}
  • Related