Exceptions - Selenium Java
Last Updated :
30 Jul, 2025
An exception is a misbehaviorevent or error that interrupts a program's standard execution flow. In Selenium, exceptions specifically arise when issues occur during test automation, such as attempting to interact with a non-existent web element or navigating to an invalid URL.
There are several benefits of using exceptions in Selenium, like:
- Prevents Test Crashes: Catching exceptions prevents tests from failing, allowing the rest of the test suite to run.
- Clear Error Feedback: Logging exceptions provides meaningful insights into what went wrong, speeding up debugging.
- Handles Dynamic Content: Web pages often change dynamically, and exception handling helps manage issues like missing or stale elements.
- Improves Maintainability: Handling exceptions makes scripts easier to update and maintain, especially in large test suites.
Selenium Exceptions and Solutions
Selenium WebDriver throws various exceptions depending on the issue. Below are the common exceptions, their causes, and how to handle them with their solutions.
Exceptions In SeleniumBelow is the base setup for initializing and closing the WebDriver, which we use across our examples.
BaseTestMain.java
Java
package Tests;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
public class BaseTestMain {
protected WebDriver driver;
// Set up the ChromeDriver
@BeforeMethod
public void setup() {
// Set the path to your chromedriver executable
System.setProperty("webdriver.chrome.driver", "C:\\path of the chromedriver\\chromedriver.exe");
// Initialize the ChromeDriver
driver = new ChromeDriver();
}
// Close the browser after each test
@AfterMethod
public void teardown() {
if (driver != null) {
driver.quit();
}
}
}
Then after that We implement the ExceptionsTest.java for the actual exception testing.
Java
package Exceptions;
import static org.testng.Assert.assertEquals;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import org.testng.annotations.Test;
import Tests.BaseTestMain;
public class ExceptionsTest extends BaseTestMain {
@Test
public void testNoSuchElementException() {
driver.get("https://www.google.com/");
try {
// Intentional incorrect locator to trigger exception
WebElement searchBox = driver.findElement(By.id("non-existent-id"));
searchBox.sendKeys("Selenium WebDriver");
} catch (WebDriverException e) {
System.out.println("Element not found: " + e.getMessage());
}
}
@Test
public void testNoSuchElementException2() {
driver.get("https://www.google.com/");
try {
// Correct locator with assertion
WebElement searchBox = driver.findElement(By.name("q"));
searchBox.sendKeys("Selenium WebDriver");
assertEquals(searchBox.isDisplayed(), true, "Search box is not displayed");
} catch (WebDriverException e) {
System.out.println("Element not found: " + e.getMessage());
}
}
@Test
public void testElementNotInteractableException() {
driver.get("https://www.google.com/");
try {
// Simulating interaction with a hidden or disabled element
WebElement hiddenElement = driver.findElement(By.cssSelector("input[aria-hidden='true']"));
hiddenElement.click();
} catch (WebDriverException e) {
System.out.println("Element not interactable: " + e.getMessage());
}
}
@Test
public void testNoAlertPresentException() {
driver.get("https://www.google.com/");
try {
Alert alert = driver.switchTo().alert();
assertEquals(alert.getText(), "Hello world!", "Alert text does not match");
alert.accept();
} catch (WebDriverException e) {
System.out.println("No alert present: " + e.getMessage());
}
}
@Test
public void testNoSuchSessionException() {
driver.get("https://www.google.com/");
driver.quit(); // Closing the session
try {
// Attempting to interact with an element after quitting the session
WebElement searchBox = driver.findElement(By.name("q"));
searchBox.sendKeys("Selenium WebDriver");
} catch (WebDriverException e) {
System.out.println("No session available: " + e.getMessage());
}
}
@Test
public void testInvalidSelectorException() {
driver.get("https://www.google.com/");
try {
// Using an invalid CSS selector to trigger exception
WebElement searchBox = driver.findElement(By.cssSelector("#$invalid-selector"));
searchBox.sendKeys("Selenium WebDriver");
} catch (WebDriverException e) {
System.out.println("Invalid selector: " + e.getMessage());
}
}
@Test
public void testStaleElementReferenceException() {
driver.get("https://www.google.com/");
WebElement searchBox = driver.findElement(By.name("q"));
searchBox.sendKeys("Selenium WebDriver");
driver.navigate().refresh(); // Refreshing the page to invalidate the element reference
try {
// Attempting to interact with a stale element
searchBox.sendKeys("Selenium WebDriver");
} catch (WebDriverException e) {
System.out.println("Stale element reference: " + e.getMessage());
}
}
}
Output:
Exception Test OutputAlternative Error Handling Techniques
While try-catch blocks are the primary way to handle exceptions, you can use other strategies to make tests more efficient:
1. Implicit Waits: Set a default wait time for all element searches to reduce NoSuchElementException.
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
2. Explicit Waits: Use WebDriverWait to wait for specific conditions (e.g., element visibility).
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("element-id")));
3. Retry Logic: Implement custom retries for flaky actions.
Java
public WebElement retryFindElement(WebDriver driver, By locator, int attempts) {
for (int i = 0; i < attempts; i++) {
try {
return driver.findElement(locator);
} catch (org.openqa.selenium.NoSuchElementException e) {
System.out.println("Retrying... Attempt " + (i + 1));
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
}
}
throw new RuntimeException("Failed to find element after " + attempts + " attempts.");
}
4. Page Object Model (POM): Encapsulate element interactions in page classes to centralize error handling.
Java
public class GooglePage {
private WebDriver driver;
private By searchBar = By.name("q");
public GooglePage(WebDriver driver) {
this.driver = driver;
}
public void enterSearchQuery(String query) {
try {
WebElement element = driver.findElement(searchBar);
element.sendKeys(query);
} catch (org.openqa.selenium.NoSuchElementException e) {
throw new RuntimeException("Search bar not found: " + e.getMessage());
}
}
}
Consequences of Skipping Exception Handling
Ignoring exceptions can lead to several problems, like
- Abrupt Test Failures: Uncaught exceptions stop execution, skipping remaining test cases and missing potential defects.
- Poor Error Reporting: Without logging, you’ll struggle to understand why a test failed, wasting time on debugging.
- Inconsistent Results: Tests may pass or fail unpredictably due to unhandled issues like timeouts or dynamic content changes.
- Reduced Scalability: Unhandled exceptions make it harder to scale test suites or integrate them into automated workflows.
Proper exception handling in Selenium is key to building efficient automation tests. By managing exceptions effectively, you ensure that tests provide useful feedback, maintainability, and consistency, even when issues arise while testing.
Similar Reads
Software Testing Tutorial Software testing is an important part of the software development lifecycle that involves verifying and validating whether a software application works as expected. It ensures reliable, correct, secure, and high-performing software across web, mobile applications, cloud, and CI/CD pipelines in DevOp
10 min read
What is Software Testing? Software testing is an important process in the Software Development Lifecycle(SDLC). It involves verifying and validating that a Software Application is free of bugs, meets the technical requirements set by its Design and Development, and satisfies user requirements efficiently and effectively.Here
11 min read
Principles of Software testing - Software Testing Software testing is an important aspect of software development, ensuring that applications function correctly and meet user expectations. From test planning to execution, analysis and understanding these principles help testers in creating a more structured and focused approach to software testing,
3 min read
Software Development Life Cycle (SDLC) Software Development Life Cycle (SDLC) is a structured process that is used to design, develop, and test high-quality software. SDLC, or software development life cycle, is a methodology that defines the entire procedure of software development step-by-step. The goal of the SDLC life cycle model is
8 min read
Software Testing Life Cycle (STLC) The Software Testing Life Cycle (STLC) is a process that verifies whether the Software Quality meets the expectations or not. STLC is an important process that provides a simple approach to testing through the step-by-step process, which we are discussing here. Software Testing Life Cycle (STLC) is
7 min read
Types of Software Testing Software testing is a important aspect of software development life-cycle that ensures a product works correctly, meets user expectations, and is free of bugs. There are different types of software testing, each designed to validate specific aspects of an application, such as functionality, performa
15+ min read
Levels of Software Testing Software Testing is an important part of the Software Development Life Cycle which is help to verify the product is working as expected or not. In SDLC, we used different levels of testing to find bugs and errors. Here we are learning those Levels of Testing in detail.Table of ContentWhat Are the Le
4 min read
Test Maturity Model - Software Testing The Test Maturity Model (TMM) in software testing is a framework for assessing the software testing process to improve it. It is based on the Capability Maturity Model(CMM). It was first produced by the Illinois Institute of Technology to assess the maturity of the test processes and to provide targ
8 min read
SDLC MODELS
TYPES OF TESTING