Selenium WebDriver Exceptions

Selenium WebDriver Exceptions

ยท

2 min read

When working with Selenium WebDriver, we may encounter various exceptions. Understanding these exceptions helps in writing robust automation scripts. Let's explore the most common Selenium WebDriver exceptions and how to handle them!

๐Ÿ”น 1. NoSuchElementException

๐Ÿ“Œ Cause: Element not found in the DOM.
โœ… Fix: Use WebDriverWait for dynamic elements.

Wait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("example")));

๐Ÿ”น 2. StaleElementReferenceException

๐Ÿ“Œ Cause: The element is no longer attached to the DOM (due to page reload, AJAX calls, etc.).
โœ… Fix: Re-locate the element before interacting.

WebElement element = driver.findElement(By.id("example"));
driver.navigate().refresh();
element = driver.findElement(By.id("example")); // Re-locate
element.click();

๐Ÿ”น 3. ElementClickInterceptedException

๐Ÿ“Œ Cause: Another element is covering the target element.
โœ… Fix: Scroll to the element before clicking.

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].scrollIntoView(true);", element);
element.click();

๐Ÿ”น 4. TimeoutException

๐Ÿ“Œ Cause: An operation took too long (e.g., waiting for an element).
โœ… Fix: Increase explicit wait time.

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(20));
wait.until(ExpectedConditions.elementToBeClickable(By.id("submit")));

๐Ÿ”น 5. WebDriverException

๐Ÿ“Œ Cause: WebDriver-related issue (e.g., browser crash, driver not started).
โœ… Fix: Ensure correct driver version and browser compatibility.

System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
WebDriver driver = new ChromeDriver();

๐Ÿ”น 6. InvalidElementStateException

๐Ÿ“Œ Cause: Trying to interact with an invisible or disabled element.
โœ… Fix: Ensure the element is enabled before interaction.

if (element.isEnabled()) {
    element.sendKeys("Test");
} else {
    System.out.println("Element is disabled");
}

๐Ÿ”น 7. SessionNotCreatedException

๐Ÿ“Œ Cause: Incompatible WebDriver and browser versions.
โœ… Fix: Update the WebDriver to match the browser version.

# Update ChromeDriver
brew install chromedriver  # For macOS

๐Ÿ’ก Pro Tip: Always use try-catch blocks to handle exceptions gracefully!

try {
    driver.findElement(By.id("submit")).click();
} catch (NoSuchElementException e) {
    System.out.println("Element not found: " + e.getMessage());
}
ย