Developers and Testers use an exception handling framework to handle exceptions in Selenium scripts. The diagram above depicts the different types of exceptions in Selenium that we commonly face while working with Selenium WebDriver.
What is an Exception?
An exception is a problem that occurs during the program's execution. When an exception occurs, the program execution stops, and the rest of the code in the program is not executed.
Exceptions must be handled because they disrupt the usual flow of a program's execution. One of the primary goals of exception handling is to prevent this break and keep the application running. On the occurrence of a certain exception, you may wish to do a set of actions.
Why Exceptions Matter
Unmanaged exceptions don't just stop test execution—they create blind spots in your test reports. Teams waste hours diagnosing failures that lack context (which element failed? Was the page loaded?). Worse, flaky tests erode trust in automation.
Types of Exceptions in Java and Selenium
There are three kinds of exceptions in Selenium and Java:
- Checked Exception: Checked exceptions are handled during compile time, and if they are not caught and handled during compile time, they cause a compilation problem.
- Unchecked Exception: A compiler does not need handling of unchecked exceptions. During compilation, the compiler ignores it.
- Error: When a scenario becomes fatal, and the software is unable to recover.
Example of an Exception in Java
Let's say our program has 5 lines, as shown below. If an exception occurs at the 3rd line, the program execution will stop, and the remaining lines, i.e., the 4th and 5th, will not be executed.
Statement1;
Statement2;
Statement3; //Exception occurred at this 3rd line
Statement4; //This line won't be executed
Statement5; //This line won't be executed
Here's a Java program code example (read the comments):
Output:
From the output, it's very clear that the Program execution stopped due to an ArithmeticException, and the last statement in the above program didn't get executed.
Handling Exceptions in Selenium Scripts
In the above program, if we want to continue the execution of the Java program, even after the exception occurs, we have to handle it. The method of handling the exception is known as Exceptional Handling. Surround the Java Statement that is throwing the Exception using the 'try … catch' block as shown in the screenshot below:
Note: The catch block in 'try .. catch' will use the respective Class required to handle the Exception. Since the exception thrown in the above program is an ArithmeticException, we have a predefined class in Java known as ArithmeticException that can handle this exception.
Now, execute the Exception-handled code and observe that the Exception will be handled and the program will continue to execute without stopping when the exception occurs:
Common Exceptions in Selenium WebDriver
From the above examples, you understand what selenium exceptions are and what happens when they occur during program execution. Now, let's explore all the different types of exceptions in Selenium that we may face while working with Selenium WebDriver.
Though there are many WebDriver exceptions in Selenium, below are the different WebDriver exceptions that we commonly face while working with Selenium:
- NoSuchElementException
- ElementNotVisibleException
- NoSuchFrameException
- NoAlertPresentException
- NoSuchWindowException
- SessionNotFoundException
- StaleElementReferenceException
- InvalidSelectorException
- ElementNotSelectableException
- TimeOutException
Now, we will explain all these Selenium WebDriver exceptions in a detailed and practical way:
1. NoSuchElementException
This exception occurs when the locators (i.e. id / xpath / css selectors, etc.) we mentioned in the Selenium Program code are unable to find the web element on the web page. There are two possibilities for getting this exception: either we have provided an incorrect locator and are trying to find the web element, or we have provided the correct locator, but the web element related to the locator is not available on the web page.
Best Practices to Handle NoSuchElementException:
- Verify that your locator is correct using browser developer tools
- Implement explicit waits to ensure the element has time to load before interaction
- Consider using a more robust locator strategy (e.g., using IDs instead of XPaths when possible)
- Use try-catch blocks to handle the exception gracefully
Click here to understand NoSuchElementException in a detailed and practical manner.
2. ElementNotVisibleException
This exception occurs when the locators (i.e. id / xpath / css selectors, etc.) we have provided in the Selenium Program code are trying to find the web element that is hidden from display on the page. For example, if there is no button displayed on the web page, and if there is HTML code related to the button, then when trying to find the button using the locators of the button by executing the Selenium Code, we get an ElementNotVisibleException.
Note: In Selenium 4, ElementNotVisibleException has been replaced with ElementNotInteractableException, which better captures scenarios where an element exists in the DOM but cannot be manipulated.
Handling Strategies:
- Use JavaScript Executor to interact with hidden elements if necessary
- Implement actions to make the element visible (like scrolling or clicking a parent element)
- Use explicit waits with ExpectedConditions.visibilityOfElementLocated()
Click here to understand ElementNotVisibleException in a detailed and practical manner.
3. NoSuchFrameException
iframe is an HTML web page inside another HTML web page. To work with the Web Elements on any iframe, we have to first switch to the iframe in Selenium and then locate the respective web elements inside the iframe. NoSuchFrameException WebDriver Exception occurs when the driver in the Selenium Program code is unable to find the frame on the web page to switch to. i.e., when the driver is switching to an invalid or non-existent iframe.
Best Practices:
- Always verify frame existence before switching
- Use explicit waits to ensure the frame is available
- Consider using frame index, name, or WebElement to switch with better reliability
- Implement proper frame navigation (switch to parent/default content when done)
Click here to understand NoSuchFrameException in a detailed and practical manner.
4. NoAlertPresentException
Alert is a type of pop-up that pops up to provide important information to users. To work with Alert pop-ups, we have to first switch to Alert and then perform operations on Alert, like reading the messages on the Alerts or Accepting the alert by pressing the 'OK' button on the alert, etc. NoAlertPresentException WebDriver Exception occurs when the driver in the Selenium Program code is unable to find the Alert on the web page to switch. i.e., when the driver is switching to an invalid or non-existing Alert pop-up.
Handling Strategies:
- Use explicit waits with ExpectedConditions.alertIsPresent()
- Implement proper checking for alert existence before interaction
- Consider using try-catch blocks to handle scenarios where alerts may or may not appear
Click here to understand NoAlertPresentException in a detailed and practical manner.
5. NoSuchWindowException
As Selenium only automates Web Applications, we will be mostly dealing with Browser Windows. A Browser Window is a square box in which a browser generally displays web pages. In order to work with the Web Elements on any Browser Pop-up Window, we have to first switch to the pop-up in Selenium and then locate the respective web elements inside the pop-up window. NoSuchWindowException WebDriver Exception occurs when the driver in the Selenium Program code is unable to find the pop-up window on the web page to switch to. i.e., when the driver is switching to an invalid or non-existent pop-up window.
Best Practices:
- Store window handles before opening new windows
- Use getWindowHandles() to get an updated list of all open windows
- Implement explicit waits to ensure new windows have time to load
- Use proper window management (close windows when done)
Click here to understand NoSuchWindowException in a detailed and practical manner.
6. SessionNotFoundException
This Exception occurs when a driver is trying to perform operations on the Web Application after the Browser is closed. It typically happens when your WebDriver session has been terminated but your code is still trying to interact with it.
Handling Strategies:
- Always use try-finally blocks to ensure proper driver quitting
- Implement checks to verify the session is active before performing operations
- Consider session reuse strategies for long-running test suites
Click here to understand SessionNotFoundException in a detailed and practical manner.
7. StaleElementReferenceException
StaleElementReferenceException WebDriver Exception occurs mainly because of page navigations between the execution of Selenium code. i.e. This exception occurs when Selenium navigates to a different page, comes back to the same old page, and performs operations on the old page.
Technically, it occurs when the element defined in the Selenium code is not found in the cache memory, and the Selenium code is trying to locate it. When we define an element on a page using Selenium, Selenium stores it in a cache memory.
The element stored in cache memory generally gets deleted when the driver navigates away to another page during Selenium code execution. On coming back to the same old page and then trying to identify the cache-removed element on the old page, we get a StaleElementReferenceException as a result.
Best Practices:
- Relocate elements after page navigation or DOM changes
- Use fluent wait with ignoring StaleElementReferenceException
- Implement retry mechanisms for flaky elements
- Consider using the Page Object Model pattern to manage element references
Click here to understand StaleElementReferenceException in a detailed and practical manner.
8. InvalidSelectorException
InvalidSelectorException WebDriver Exception is a subclass of the NoSuchElementException class, and it occurs when a selector is incorrect or syntactically invalid. This exception occurs commonly when XPATH locator is used.
Handling Strategies:
- Validate selector syntax before use
- Use browser developer tools to test selectors
- Consider using more robust selector strategies (CSS instead of complex XPaths)
- Implement proper error handling for selector issues
9. ElementNotSelectableException
This exception comes under the InvalidElementStateException class. The ElementNotSelectableException indicates that the web element is present in the web page but cannot be selected. This often happens with disabled form elements or elements that are not designed to be selectable.
Best Practices:
- Check the element state before attempting interaction
- Use JavaScript Executor for special cases if needed
- Implement proper waiting strategies to ensure the element is ready for interaction
- Consider alternative interaction methods if the element cannot be made selectable
10. TimeOutException
This exception happens when a command takes longer to complete than the wait time. Waits are mostly utilized in WebDriver to avoid the ElementNotVisibleException error.
Sometimes the test page may not entirely load before the following instruction in the program. If WebDriver attempts to locate an element on a webpage before it has fully loaded, the error ElementNotVisibleException is thrown. Wait instructions have been introduced to avoid this issue.
Handling Strategies:
- Adjust wait times based on application performance
- Use dynamic waits with appropriate conditions
- Consider breaking down complex actions into smaller steps with individual waits
- Implement proper error handling for timeout scenarios
New Exceptions in Selenium 4
Selenium 4 introduced several new exceptions and deprecated some old ones to improve error handling and provide more specific information about failures. Here are some important exceptions in Selenium 4 that weren't in the original list:
1. DetachedShadowRootException
This exception is thrown when trying to access the shadow root of an element after it's been detached from the DOM. Shadow DOM is becoming increasingly common in modern web applications, and Selenium 4 provides better support for working with shadow DOM elements.
2. InsecureCertificateException
This exception occurs when navigation causes the browser to encounter a certificate warning, usually from an expired or invalid TLS certificate. Selenium 4 provides better handling for secure contexts.
3. InvalidCoordinatesException
Thrown when incorrect coordinates are provided to an interaction operation. This often occurs when trying to perform mouse actions at invalid screen positions.
4. InvalidSessionIdException
This exception indicates that the given session ID is not in the list of active sessions, meaning the session either doesn't exist or is no longer active.
Advanced Exception Handling Strategies
Using Explicit Waits
One of the most effective ways to handle many Selenium exceptions is to implement explicit waits. Here's an example:
java
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("element-id")));
This approach waits up to 10 seconds for an element to become visible before throwing an exception, which can help prevent NoSuchElementException and ElementNotVisibleException.
Implementing Custom Expected Conditions
For more complex scenarios, you can create custom expected conditions:
java
public static ExpectedCondition<Boolean> elementHasClass(final By locator, final String className) {
return new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver driver) {
try {
String classes = driver.findElement(locator).getAttribute("class");
return classes != null && classes.contains(className);
} catch (NoSuchElementException | StaleElementReferenceException e) {
return false;
}
}
@Override
public String toString() {
return "element located by " + locator + " to have class " + className;
}
};
}
Retry Mechanisms for Flaky Tests
For handling intermittent issues that cause exceptions, implementing a retry mechanism can be helpful:
java
public WebElement findElementWithRetry(By by, int maxRetries) {
int retries = 0;
while (retries < maxRetries) {
try {
return driver.findElement(by);
} catch (StaleElementReferenceException | NoSuchElementException e) {
retries++;
if (retries == maxRetries) {
throw e;
}
// Wait a bit before retrying
try {
Thread.sleep(500);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
throw new RuntimeException("Thread was interrupted", ie);
}
}
}
throw new NoSuchElementException("Element not found after " + maxRetries + " retries");
}
Visualizing and Analyzing Automated Test Results
Proper test reporting is crucial for understanding and managing exceptions in Selenium tests. When tests fail due to exceptions, comprehensive reporting helps identify patterns and root causes more efficiently.
Benefits of Modern Reporting for Exception Analysis
Modern reporting tools provide several advantages for managing automated test results:
- Visual Representation: Charts and graphs help visualize test execution data, making it easier to spot trends in exception occurrences.
- Detailed Logs: Comprehensive logs with exception details help with debugging and root cause analysis.
- Screenshot Capture: Automatic screenshot capture at the moment of exception occurrence provides visual context.
- Historical Data: Tracking exceptions over time helps identify recurring issues and measure the effectiveness of exception handling strategies.
Popular Reporting Frameworks for Selenium Tests
Several reporting frameworks can help visualize and analyze Selenium test results:
- Extent Reports: An open-source reporting library that offers rich HTML reports with detailed test execution data, screenshots, and logs.
- Allure Reports: Provides detailed test reports with severity indicators, attachments, and trend analysis.
- TestNG Reports: Built-in reporting capability with TestNG that generates HTML reports showing test execution details.
- JUnit Reports: Simple HTML reports that provide basic information about test execution.
- ReportPortal: An AI-powered test reporting dashboard that provides real-time reporting and analytics.
Integrating a robust reporting framework with your Selenium tests helps track exceptions and understand their impact on test reliability.
Centralized Exception Reporting
While frameworks like Allure capture individual test results, teams need tools like TestQuality to:
- Correlate exceptions across test runs (e.g., "NoSuchElementException" occurs 70% on Chrome but 5% on Firefox).
- Auto-tag flaky tests based on exception patterns (e.g., StaleElementReferenceException = likely needs a wait).
- Trace exceptions to requirements (e.g., "Login failures map to Auth0 integration tests").
Best Practices for Exception Handling in Selenium
1. Use a Proactive Approach to Avoid Exceptions
Rather than focusing solely on handling exceptions, implement strategies to prevent them:
- Use reliable locators (prefer IDs over XPaths when possible)
- Implement proper waits (explicit over implicit)
- Structure your test code to anticipate potential issues
2. Scale Your Exception Handling Strategy
Not all exceptions require the same level of handling:
- Critical path: Implement detailed handling with recovery mechanisms
- Less critical areas: Simple logging may be sufficient
3. Log Exceptions Properly
Ensure exceptions provide useful information for debugging:
- Include context (what action was being attempted)
- Capture relevant state (screenshots, DOM snapshots)
- Include timestamps for sequence analysis
4. Implement Recovery Mechanisms
For some exceptions, automatic recovery may be possible:
- Retry mechanisms for flaky elements
- Page refreshes for stale elements
- Session recreation for session exceptions
5. Use Framework-Level Exception Handling
Implement exception handling at the framework level to provide consistent behavior:
- Custom exception wrappers that add context
- Centralized logging and reporting
- Standard recovery mechanisms
In Summary
Exception handling is a critical component of any Java application or Selenium script. By handling exceptions in Selenium intelligently, we can create resilient and optimal programming. It is also excellent practice to handle exceptions in a script, which will provide you with a more detailed report when a program fails for whatever reason.
Selenium exceptions shouldn't be ignored, as they break program execution. Adding waits can control some cases, such as 'NoSuchElementException', 'ElementNotFoundException', and 'ElementNotVisibleException'.
Selenium and Automation Testing
Selenium is an automation framework backed by top web browser developers (Google, Microsoft, Apple, Mozilla). It is safe to say that Selenium is one of the best ways to automate our web browsers for now.
We recently took a Close Look at Selenium's Benefits and Disadvantages, made a short list of several Selenium Testing Tools, including free and non-free ones, and then came up with a comparison of two Selenium best ones – Robot Framework and Katalon Studio.
TestQuality, thanks to its TestQuality Command Line Interface, allows you to upload your automated test results from Selenium to TestQuality. Automated test results may be its output in JUnit XML format, which most test automation tools will provide. Test result attachments and related defects are also supported through test name tags or console outputs. Join now and Try TestQuality for Free!