'How can I ignore the exception if the item is not found? Selenium(selenide)

Several of my tests refer to importBrokerCheckBox. But not all tests have to find it, because he must be absent. That is, if the element is on the page, then we must click on it, and if it is not there, we must go further through the code.But below code doesn't work and throws exception - xpath not found

importBrokerCheckBox = $x(".//div[text()='Брокер']/../../../preceding-sibling::span//span[@aria-label=\"caret-down\"]"),

    if (importBrokerCheckBox.isDisplayed());
    {
        importBrokerCheckBox.click();
    }

    if (importBrokerSettingsCheckbox.isDisplayed());
    {
        importBrokerSettingsCheckbox.click();
    }


Solution 1:[1]

There are basically two options:

  1. try/catch block - if element is not found (NoSuchElementException occured) the catch block code is executed (can be empty ofc).
  2. using List<WebElement> elements = driver.findElements(By.by); if no element is found, NoSuchElementException is NOT thrown and the list stays empty like new ArrayList<WebElement>().

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 pburgr