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 as we explained in our previous article: Different types of Selenium WebDriver 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.

Selenium Webdriver Exceptions | Solving Webdriver Errors

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.

Test Management Tool for Manual and Test Automation | TestQuality

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());
}

 

Benefits of Managing Selenium Test Results with TestQuality

While mastering Selenium exceptions is crucial for robust test automation, effectively managing your test results can make the difference between good and great testing practices. TestQuality's comprehensive test management platform transforms how teams handle Selenium automated testing results.

 TestQuality offers the option to import Selenium automation test results and other main automation frameworks.

▪️ Centralized Test Results Management

Consolidate all your Selenium test executions in one accessible location. Say goodbye to scattered logs and manual reporting processes that slow down your testing workflow.

Software Testing | Test Run Results | Test Management | TestQuality

TestQuality's Test Run Overview, offers Run Information and Details.

▪️ Enhanced Test Traceability

Create clear connections between your Selenium tests, requirements, and test cases. This end-to-end traceability makes audit preparation straightforward and helps maintain testing compliance.

▪️ Real-Time Testing Analytics

Access detailed dashboards and reports that provide immediate insights into your Selenium test execution. Identify patterns, track failure rates, and make informed decisions about your testing strategy.

▪️ Seamless Team Collaboration

Share test results and insights across your entire team through an intuitive interface that promotes collaborative testing practices.

▪️ Streamlined Test Organization

Efficiently manage your Selenium test suites, maintain execution history, and organize your testing assets in a structured environment.

Ready to transform your Selenium testing process?
Start managing your automated tests with TestQuality today. Visit our Selenium Automation Guide to learn more about maximizing your test automation efficiency.

Transform Your Testing Process Today
Ready to take control of your Selenium testing? TestQuality offers a powerful, yet intuitive Test Management tool that streamlines your entire test management workflow.

Start your free trial now and experience firsthand how our modern solution can enhance your team's testing efficiency. No credit card required – Start Free and get instant access to all premium features for 14 days. 

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.

Remember that you can start to transform your Selenium Testing thanks to TestQuality, that offers a powerful, yet intuitive Test Management tool that streamlines your entire test management workflow.

Always remember to prepare for these questions in interviews, as they are common topics of discussion. Happy testing!

Newest Articles

Ministry of Testing - ¨TestQuality named Tool of the Week
TestQuality Named “Tool of the Week” by Ministry of Testing!
We’re excited to share some big news with our community of QA professionals, software testers, and developers: TestQuality has been named "Tool of the Week" by the Ministry of Testing (MoT), one of the most respected communities in the software testing world! You can find the mention featured directly on the Ministry of Testing homepage and a dedicated… Continue reading TestQuality Named “Tool of the Week” by Ministry of Testing!
Top Gherkin BDD Tools for Modern Test Management in 2025
Software quality assurance has evolved significantly in recent years, with behavior-driven development (BDD) emerging as a powerful methodology for aligning technical teams with business objectives. At the center of this evolution sits Gherkin, a simple yet powerful specification language that bridges the communication gap between technical and non-technical stakeholders and simplifies the creation and maintenance… Continue reading Top Gherkin BDD Tools for Modern Test Management in 2025
Playwright Vs Jest | Visual regression testing. Flakiness and Test Management
Visual Regression Testing with Playwright Vs. Others
What is Playwright? Playwright is a Microsoft-created NodeJS package with capabilities that are quite similar to Puppeteer. Both libraries enable you to automate browser-based tasks. With Playwright, you can launch or connect to a Chrome, Edge, Safari, or Firefox browser and exchange instructions. The DevTools protocol (for Chrome browsers) and a bespoke protocol (for Firefox and… Continue reading Visual Regression Testing with Playwright Vs. Others

© 2025 Bitmodern Inc. All Rights Reserved.