⚠️Exceptions

What are Exceptions? 💥

Exceptions are errors that disrupt the normal flow of program execution in Selenium scripts. They indicate something went wrong.

Why Handle Exceptions? 🛡️

  • Avoid script crashes from uncaught exceptions

  • Gracefully recover or log issues when they occur

  • Improve script robustness by anticipating problems

What are some common exceptions?

❌ NoSuchElementException: The findElement() method could not locate the element using the provided locator. Usually due to an invalid locator.

❌ NoSuchWindowException: Trying to switch to a window that does not exist.

❌ NoSuchFrameException:

Trying to switch to an iframe that does not exist.

❌ NoAlertPresentException: Trying to switch to an alert when no alert is present.

❌ StaleElementReferenceException: The element is no longer attached to the DOM. This can happen if the page is reloaded or the element is removed.

❌ ElementNotVisibleException: The element is present in the DOM but is not visible, so it cannot be interacted with.

❌ ElementNotSelectableException: The element is present but disabled, so it cannot be clicked or selected.

❌ WebDriverException: A generic Selenium exception is often due to trying to interact with an element after the browser has closed.

❌ TimeoutException: An operation did not complete in the specified time. Commonly encountered with explicit waits.

❌ InvalidSelectorException: The provided locator strategy is invalid, such as using an incorrect XPath syntax.

So in summary, the most common exceptions you'll encounter while automating web pages using Selenium WebDriver are related to:

  • Locating elements

  • Switching between windows/frames/alerts

  • Element visibility/enablement

  • Timeouts

  • Invalid locators

Handling Exceptions in Selenium 🪛

  • try / catch blocks to catch and handle exceptions

  • Log exceptions with e.printStackTrace() for debugging

  • Rethrow exceptions after handling for additional logic

  • finally block to execute cleanup code like closing browser

Example Exception Handling ✅

try {

  driver.findElement(By.id("button")).click();

} catch (NoSuchElementException e) {

  System.out.println("Element not found!");
  
} finally {

  driver.quit();

}

So in summary, exception handling helps recover and continue when errors happen in Selenium scripts! 💪

Last updated