Top 10 Selenium Exceptions and How to Handle Them

Get Started

with $0/mo FREE Test Plan Builder or a 14-day FREE TRIAL of Test Manager

Automation testing has become an essential part of software development. One of the most widely used tools in this domain is Selenium. However, as with any programming framework, Selenium comes with its own set of challenges, particularly when it comes to exceptions. This guide will explore the top 10 Selenium exceptions, how to handle them effectively, and why understanding these exceptions is crucial for every automation tester.

What is an Exception?

An exception is essentially an unwanted event that occurs during the execution of a program, disrupting its normal flow. For example, consider trying to divide a number by zero; this will result in an Arithmetic Exception. Similarly, accessing an element outside the bounds of an array will trigger an ArrayOutOfBound Exception. These errors can occur in any automation script, making exception handling a critical skill for automation testers.

Types of Exceptions

In programming, exceptions can be broadly categorized into two types: checked and unchecked exceptions.

  • Checked Exceptions: These are exceptions that are checked at compile-time. For instance, if you try to access a file that does not exist, the compiler will throw a "File Not Found" exception.
  • Unchecked Exceptions: These occur at runtime and are not checked by the compiler. An example is a logic error, such as trying to access an array element that is out of bounds, which results in an ArrayIndexOutOfBoundsException.

Typical Flow of Exceptions

Understanding the hierarchy of exceptions in Java helps in grasping how Selenium exceptions work. The base class is Throwable, which can be divided into two main categories: Exceptions and Errors. Errors are typically beyond user control (like stack overflow), while exceptions can be handled.

How to Handle Exceptions

Handling exceptions in Java can be achieved through several methods:

  • Try-Catch Block: This is the most common method. You can wrap your code in a try block and catch specific exceptions in the catch block. For instance, if you suspect an ArrayIndexOutOfBoundsException might occur, you can catch it and handle it accordingly.
  • Try-Catch-Finally Block: This is similar to the try-catch block but includes a finally block that will execute regardless of whether an exception occurred.
  • Throw Keyword: You can also use the throw keyword to create a custom exception and throw it when certain conditions are met.

Top 10 Selenium Exceptions

Now, let's dive into the top 10 exceptions you may encounter while working with Selenium:

  • NotFoundException
  • NoSuchWindowException
  • NoSuchFrameException
  • NoSuchElementException
  • NoAlertPresentException
  • TimeoutException
  • StaleElementReferenceException
  • InvalidElementStateException
  • ElementNotVisibleException
  • ElementNotSelectableException
  • SessionNotFoundException

Handling the Top 10 Selenium Exceptions

Now, let's take a look at how to handle the top exceptions you may encounter while working with Selenium:

NotFoundException:
This occurs when the WebDriver tries to access an element that is not found in the DOM.

Example: If you attempt to locate an element using an incorrect ID, like this:
WebElement element = driver.findElement(By.id("nonExistentId"));

To handle this exception, you can use a try-catch block: 
try {
WebElement element = driver.findElement(By.id("nonExistentId"));
} catch (NotFoundException e) {
System.out.println("Element not found: " + e.getMessage());
}

NoSuchWindowException:
Triggered when the WebDriver attempts to switch to a window that is not available.

Example: After closing a window, if you try to switch back to it:
driver.switchTo().window("nonExistentWindow");

Handle it like this: 
try {
driver.switchTo().window("nonExistentWindow");
} catch (NoSuchWindowException e) {
System.out.println("Window not found: " + e.getMessage());
}

NoSuchFrameException:
This happens when the WebDriver tries to switch to a frame that does not exist.

Example: Attempting to switch to a frame using an invalid name:
driver.switchTo().frame("invalidFrameName");

To handle it:
try {
driver.switchTo().frame("invalidFrameName");
} catch (NoSuchFrameException e) {
System.out.println("Frame not found: " + e.getMessage());
}

NoSuchElementException:
This exception is raised when the WebDriver cannot find an element during runtime, often due to incorrect locators.

Example: Using a locator that doesn't match any elements:
WebElement element = driver.findElement(By.xpath("//div[@class='nonExistentClass']);

Handle it by:
try {
WebElement element = driver.findElement(By.xpath("//div[@class='nonExistentClass']"));
} catch (NoSuchElementException e) {
System.out.println("Element not found: " + e.getMessage());
}

NoAlertPresentException:
Occurs when the WebDriver attempts to switch to an alert that is not present.

Example: Trying to switch to an alert that has not appeared:
driver.switchTo().alert();

Handle it with:
try {
driver.switchTo().alert();
} catch (NoAlertPresentException e) {
System.out.println("No alert present: " + e.getMessage());
}

TimeoutException:
This happens when a command does not complete in the specified time, often encountered when working with waits.

Example: Setting a wait for an element that doesn't appear in time:
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("elementId")));

Handle it like this:
try {
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("elementId")));
} catch (TimeoutException e) {
System.out.println("Operation timed out: " + e.getMessage());
}

StaleElementReferenceException:
This indicates that the referenced element is no longer present in the DOM, usually due to navigation or DOM refresh.

Example: Trying to interact with an element after navigating away:
WebElement element = driver.findElement(By.id("elementId"));
driver.navigate().refresh();
element.click();

Handle it with:
try {
element.click();
} catch (StaleElementReferenceException e) {
System.out.println("Stale element reference: " + e.getMessage());
}

InvalidElementStateException:
This occurs when the element is present but is in an invalid state for the intended action.

Example: Trying to click a disabled button:
WebElement button = driver.findElement(By.id("disabledButton")); button.click();

To handle this exception, you can use a try-catch block as follows:
try {
button.click();
} catch (InvalidElementStateException e) {
System.out.println("Element is not in a valid state: " + e.getMessage());
}

ElementNotVisibleException:
This occurs when the element is present in the DOM but is not visible (i.e., cannot be interacted with).

Example: Attempting to click on an element that is hidden:
WebElement hiddenElement = driver.findElement(By.id("hiddenElement")); hiddenElement.click();

To handle this exception, consider using a wait until the element becomes visible:
try {
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("hiddenElement"))).click();
} catch (ElementNotVisibleException e) {
System.out.println("Element is not visible: " + e.getMessage());
}

ElementNotSelectableException:
This exception is thrown when trying to select an element that cannot be selected.

Example: Attempting to select a checkbox that is disabled:
WebElement checkbox = driver.findElement(By.id("disabledCheckbox")); checkbox.click();

To handle this exception, check if the element is enabled before trying to click:
try {
if (checkbox.isEnabled()) {
checkbox.click();
} else {
System.out.println("Checkbox is not selectable");
}
} catch (ElementNotSelectableException e) {
System.out.println("Element cannot be selected: " + e.getMessage());
}

SessionNotFoundException:
This occurs when the WebDriver tries to interact with a session that is no longer available, often after quitting the browser.

Example: Attempting to perform an action after the browser has been closed:
driver.quit(); driver.get("http://example.com");

To handle this exception, ensure that actions are not attempted after quitting the driver:
try {
driver.quit();
driver.get("http://example.com");
} catch (SessionNotFoundException e) {
System.out.println("Session not found: " + e.getMessage());
}

More reading

Conclusion

Understanding and handling exceptions in Selenium is not just a programming skill; it’s a critical part of becoming an effective automation tester. The top 10 exceptions highlighted in this guide are frequently encountered and knowing how to handle them will significantly improve your automation scripts. Always remember to prepare for these questions in interviews, as they are common topics of discussion. Happy testing!

Newest Articles

Beyond Regression Testing: Rethinking Risk in Modern Software Development
Picture this: You’ve just deployed a new feature at work, and you’re buzzing with excitement. But suddenly, you hear whispers of a critical bug in the old functionality. That gut-wrenching moment reminds us how important it is to address regression testing. In this post, we’ll delve into the legacy views of regression testing, explore its modern implications, and highlight why risk management is the real MVP in ensuring robust software development.
Top 10 Selenium Exceptions and How to Handle Them
Automation testing has become an essential part of software development. One of the most widely used tools in this domain… Continue reading Top 10 Selenium Exceptions and How to Handle Them
Software Testisng Functional and Non-Functional Testing Case Examples
10 Real Case Examples for Software Test Plans
Software testing is a critical phase in the software development lifecycle, ensuring that the final product meets the desired quality standards. To… Continue reading 10 Real Case Examples for Software Test Plans

© 2025 Bitmodern Inc. All Rights Reserved.