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());
}