Open In App

Exceptions - Selenium Java

Last Updated : 30 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

common-Selenium-WebDriver-exceptions
Exceptions In Selenium

Below 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-of-Selenium-WebDriver-output
Exception Test Output

Alternative 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

  1. Abrupt Test Failures: Uncaught exceptions stop execution, skipping remaining test cases and missing potential defects.
  2. Poor Error Reporting: Without logging, you’ll struggle to understand why a test failed, wasting time on debugging.
  3. Inconsistent Results: Tests may pass or fail unpredictably due to unhandled issues like timeouts or dynamic content changes.
  4. 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.


Article Tags :

Similar Reads