In Selenium automation, we often encounter different types of exceptions when elements are not available or cannot be interacted with. Exceptions in Java are subclasses of the Throwable class, and handling them properly is crucial to ensure smooth and continuous execution of test scripts.
Some commonly faced exceptions include:
- StaleElementReferenceException
- NoSuchElementException
- ArithmeticException
For example, a StaleElementReferenceException occurs when an element is present in the DOM (Document Object Model) but is no longer attached to the active user interface. This usually happens when the page gets refreshed or dynamically updated.
We can handle StaleElementReferenceException in Selenium by refreshing the page or by re-locating the element before performing further actions. This exception usually occurs when the DOM has changed (for example, after a page reload, AJAX update, or navigation) and the previously referenced element is no longer valid.
A common approach is:
- Refresh the page (as a last resort) and then re-locate the element.
- Re-locate the element whenever you need it, instead of storing it for a long time.
- Use WebDriverWait with
ExpectedConditions.refreshedorExpectedConditions.visibilityOfElementLocatedto wait for the element to be available again.
Below, I’ve provided a sample script to demonstrate how to handle a stale element exception:
Example – Handling StaleElementReferenceException in Selenium (Java):
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
public class StaleElementExample {
public static void main(String[] args) {
// Initialize WebDriver
WebDriver driver = new ChromeDriver();
driver.get(“https://example.com”);
// Explicit wait object
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
try {
// Locate the element and wait until clickable
WebElement element = wait.until(
ExpectedConditions.elementToBeClickable(By.id("dynamicElement"))
);
element.click();
} catch (StaleElementReferenceException e) {
System.out.println("Caught StaleElementReferenceException! Refreshing page...");
// Refresh the page
driver.navigate().refresh();
// Re-locate element after refresh and wait until clickable
WebElement element = wait.until(
ExpectedConditions.elementToBeClickable(By.id("dynamicElement"))
);
element.click();
}
driver.quit();
}
}