user3326175 user3326175 - 2 years ago 107
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

, 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
. I dont want to go with
as it takes a lot of time.

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download