Exception Handling in Selenium

  

What is Exception Handling in Selenium?

Exception handling in Selenium Java is the process of detecting, catching, and resolving unexpected events that disrupt test execution — like elements not found, timeouts, browser crashes, etc.

We handle exceptions using:

  • try-catch blocks

  • Custom methods

  • WebDriverWait + ExpectedConditions

  • Taking screenshots

  • Logging exceptions


Common Exception Handling Approach

try {
    // Selenium code that may throw exception
} catch (SpecificException e) {
    // Handle it: log, retry, screenshot, etc.
}


Example: Handle Multiple Exceptions in Selenium Java

import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.*;
import java.io.File;
import java.io.IOException;
import java.time.Duration;
import org.apache.commons.io.FileUtils;

public class ExceptionHandlingDemo {

    public static void main(String[] args) {
        WebDriver driver = new ChromeDriver();

        try {
            driver.get("https://example.com");

            // Wait for element
            WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
            WebElement button = wait.until(ExpectedConditions.elementToBeClickable(By.id("submit")));

            // Interact with element
            button.click();

        } catch (NoSuchElementException e) {
            System.out.println("Element not found: " + e.getMessage());
            takeScreenshot(driver, "NoSuchElement");

        } catch (TimeoutException e) {
            System.out.println("Element not clickable in time: " + e.getMessage());
            takeScreenshot(driver, "Timeout");

        } catch (ElementClickInterceptedException e) {
            System.out.println("Element click intercepted: " + e.getMessage());
            takeScreenshot(driver, "ClickIntercepted");

        } catch (Exception e) {
            System.out.println("Unexpected exception: " + e.getMessage());
            takeScreenshot(driver, "UnknownError");

        } finally {
            driver.quit();
        }
    }

    public static void takeScreenshot(WebDriver driver, String fileName) {
        File src = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        try {
            FileUtils.copyFile(src, new File("./screenshots/" + fileName + ".png"));
            System.out.println("Screenshot saved: " + fileName + ".png");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


Output:

  • Catches and prints exception

  • Takes screenshot on failure

  • Always closes browser (with finally)


Best Practices for Handling Exceptions

PracticeWhy?
Catch specific exceptionsAvoids masking real issues
Use WebDriverWaitPrevents NoSuchElement and TimeoutException
Use try-catch-finallyEnsures browser closes properly
Take screenshot on failureFor easier debugging of test failures
Use logs or reportsHelps in reporting and root cause analysis
Use reusable exception handlersKeeps test code clean and DRY (Don't Repeat Yourself)