user3326175 user3326175 - 14 days ago 6
Java Question

How to handle NoSuchElementException in Web Driver Java. I dont want to end test if element is not visible

I'm trying to identify an element. If the element is there, i will click and do some operation. If the element is not there, I just it need to record a message.

I have used

try
/
catch
, but the test fails when the element is not there. Could someone help me here. The below code throws an exception after waiting for the default timeout.

Note: Same question has been posted already. but only solution is to use
findElements
. I dont want to go with
findElements
as it takes a lot of time.

try{
elemToFind = driver.findelement(By.xpath(".//div[@id='rightitems']");
elementstatus = elemToFind.isDisplayed() || elemToFind.isEnabled();
elemToFind.click();
} catch (NoSuchElementException e) {
report.updateTestLog("Element is not available", Status.FAIL);
}

Answer

Make absolutely sure you have imported org.openqa.selenium.NoSuchElementException and NOT java.util.NoSuchElementException.

Then it can't fail on the element missing. If it does, it probably fails with ElementNotVisibleException which you can prevent by testing your elementStatus before click()ing.