⭐ Handling Exceptions in Selenium Test Scripts
Selenium interacts with dynamic web pages, and unexpected behavior (slow loading, missing elements, timing issues) often leads to exceptions.
Proper exception handling helps your test scripts run more reliably, more cleanly, and with fewer failures.
๐ท 1. What Is an Exception?
An exception is an error that occurs during test execution and interrupts your script unless you handle it.
In Java, exceptions are handled using:
try {
// normal code
} catch (Exception e) {
// what to do when error occurs
} finally {
// always executed (optional)
}
๐ท 2. Common Exceptions in Selenium
✔ NoSuchElementException
Element not found on the page.
✔ TimeoutException
Explicit wait exceeded while waiting for a condition.
✔ StaleElementReferenceException
Element becomes outdated (DOM changed).
✔ ElementNotInteractableException
Element is present but not ready for interaction.
✔ WebDriverException
General driver-level failure (browser crash, session issue).
๐ท 3. Using Try-Catch Blocks in Selenium Tests
✔ Handling Missing Elements
try {
WebElement element = driver.findElement(By.id("submit"));
element.click();
} catch (NoSuchElementException e) {
System.out.println("Submit button not found!");
}
๐ท 4. Using Explicit Waits to Prevent Exceptions
Explicit waits avoid timing issues.
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
try {
WebElement button = wait.until(ExpectedConditions.elementToBeClickable(By.id("submit")));
button.click();
} catch (TimeoutException e) {
System.out.println("Element did not become clickable on time.");
}
๐ท 5. Handling StaleElementReferenceException
Happens when the page DOM updates.
✔ Retry logic:
public void clickWithRetry(By locator) {
int attempts = 0;
while (attempts < 3) {
try {
driver.findElement(locator).click();
break;
} catch (StaleElementReferenceException e) {
attempts++;
}
}
}
๐ท 6. Handling Multiple Exceptions
You can catch specific exceptions first, then a general one.
try {
driver.findElement(By.id("login")).click();
} catch (NoSuchElementException e) {
System.out.println("Login button missing!");
} catch (ElementNotInteractableException e) {
System.out.println("Login button not clickable yet!");
} catch (Exception e) {
System.out.println("Unexpected error: " + e);
}
๐ท 7. Using Finally Block for Cleanup
try {
driver.get("https://example.com");
} catch (WebDriverException e) {
System.out.println("Browser error occurred");
} finally {
driver.quit(); // always executed
}
๐ท 8. Using Custom Exception Handling
You can wrap Selenium actions into reusable safe functions.
public boolean safeClick(By locator) {
try {
driver.findElement(locator).click();
return true;
} catch (Exception e) {
System.out.println("Could not click: " + e.getMessage());
return false;
}
}
๐ท 9. Taking Screenshots on Failure
Useful for debugging.
try {
driver.findElement(By.id("order")).click();
} catch (Exception e) {
TakesScreenshot ts = (TakesScreenshot) driver;
File screenshot = ts.getScreenshotAs(OutputType.FILE);
System.out.println("Screenshot taken due to failure.");
}
๐ท 10. Using Test Framework Features (Best Practice)
✔ TestNG
Use @AfterMethod with ITestResult to capture failures:
@AfterMethod
public void tearDown(ITestResult result) {
if (ITestResult.FAILURE == result.getStatus()) {
// take screenshot
}
}
✔ JUnit
Use Rules / Extensions for global exception handling.
⭐ Summary
Exception What it Means How to Handle
NoSuchElementException Element missing Waits, try-catch
TimeoutException Wait exceeded Increase timeout, improve waits
StaleElementReferenceException DOM changed Retry logic
ElementNotInteractableException Element not ready Explicit wait, scrolling
WebDriverException Browser/driver failure Restart driver, cleanup
Learn Selenium with JAVA Training in Hyderabad
Read More
Using Loops and Conditions to Control Test Flow
Java Basics for Selenium Testers
Introduction to TestNG Annotations
Visit Our Quality Thought Institute in Hyderabad
Subscribe by Email
Follow Updates Articles from This Blog via Email
No Comments