Try...catch exception handling

Now, sometimes the user will want to trap an exception instead of throwing it, and perform some other action such as retry, reload page, cleanup dialogs, and so on. In cases like that, the user can use try...catch in Java to trap the exception. The action would be included in the try clause, and the user can decide what to do in the catch condition.

Here is a simple example that uses the ExpectedConditions method to look for an element on a page, and only return true or false if it is found. No exception will be raised:

/**
* elementExists - wrapper around the WebDriverWait method to
* return true or false

*
* @param element
* @param timer
* @throws Exception
*/
public static boolean elementE
xists(WebElement element, int timer) {
try {
WebDriver driver = CreateDriver.getInstance().getCurrentDriver();
WebDriverWait exists = new WebDriverWait(driver, timer);

exists.until(ExpectedConditions.refreshed(
ExpectedConditions.visibilityOf(element)));
return true;
}

catch (StaleElementReferenceException |
TimeoutException |
NoSuchElementException e) {

return false;
}
}

In cases where the element is not found on the page, the Selenium WebDriver will return a specific exception such as ElementNotFoundException. If the element is not visible on the page, it will return ElementNotVisibleException, and so on. Users can catch those specific exceptions in a try...catch...finally block, and do something specific for each type (reload page, re-cache element, and so on):

try {
....
}

catch(ElementNotFoundException e) {
// do something
}

catch(ElementNotVisibleException f) {
// do something else
}

finally {
// cleanup
}
The Java tutorial on try...catch is located at https://docs.oracle.com/javase/tutorial/essential/exceptions/try.html.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.59.163