---Advertisement---

Comprehensive Guide to Exception Handling in Selenium WebDriver with Examples Best 2025

By Manisha

Updated On:

---Advertisement---
Comprehensive Guide to Exception Handling

What is an Exception?

Comprehensive Guide to Exception Handling: An exception is an unexpected event that occurs during the execution of a program. It disrupts the normal flow of the application. In Selenium automation, exceptions occur due to interaction failures, browser issues, element unavailability, etc.

Proper handling of exceptions ensures your test script doesn’t crash abruptly and improves the stability of your automation suite.


Table of Contents:

  1. What is an Exception?
  2. Types of Exceptions in Selenium
  3. Exception Handling Techniques in Selenium
  4. Exception Display Methods
  5. Summary

Comprehensive Guide to Exception Handling: Below is a list of the most commonly encountered exceptions in Selenium:

Exception NameDescription
1. ElementNotVisibleExceptionThe element exists in the DOM but is hidden
2. ElementNotSelectableExceptionThe element is present but not selectable
3. NoSuchElementExceptionThe element could not be found in the DOM
4. NoSuchFrameExceptionThe target frame does not exist
5. NoAlertPresentExceptionNo alert is present to switch to
6. NoSuchWindowExceptionThe target window does not exist
7. StaleElementReferenceExceptionThe element is detached from the current DOM
8. SessionNotFoundExceptionWebDriver is still acting after the session was quit
9. TimeoutExceptionCommand did not finish in the expected time
10. WebDriverExceptionGeneric WebDriver error after closing the browser
11. ConnectionClosedExceptionDriver disconnection occurred
12. ElementClickInterceptedExceptionAnother element is blocking the clickable one
13. ElementNotInteractableExceptionElement cannot be interacted with
14. ErrorInResponseExceptionIssue while communicating with Firefox extension
15. UnknownServerExceptionServer returns an error without a stack trace
16. ImeActivationFailedExceptionIME engine activation failed
17. ImeNotAvailableExceptionIME support not available
18. InsecureCertificateExceptionCertificate issue like expired or invalid SSL
19. InvalidArgumentExceptionArgument type is not as expected
20. InvalidCookieDomainExceptionCookie set for an invalid domain
21. InvalidCoordinatesExceptionInvalid coordinates provided for interaction
22. InvalidElementStateExceptionElement is in a state that cannot be interacted with
23. InvalidSessionIdExceptionSession ID is invalid or inactive
24. InvalidSwitchToTargetExceptionTarget window/frame does not exist
25. JavascriptExceptionJavaScript execution failed
26. JsonExceptionSession not created or returned invalid JSON
27. NoSuchAttributeExceptionAttribute not found in the element
28. MoveTargetOutOfBoundsExceptionTarget is out of screen/document bounds
29. NoSuchContextExceptionUsed in mobile testing contexts
30. NoSuchCookieExceptionCookie with the given path does not exist
31. NotFoundExceptionElement not found on the DOM
32. RemoteDriverServerExceptionServer fails due to improper capability definitions
33. ScreenshotExceptionUnable to take screenshot
34. SessionNotCreatedExceptionSession could not be created
35. UnableToSetCookieExceptionFailed to set cookie in driver
36. UnexpectedTagNameExceptionIncorrect tag name used for element
37. UnhandledAlertExceptionAlert appears but not handled properly
38. UnexpectedAlertPresentExceptionUnexpected alert appeared
39. UnknownMethodExceptionMethod does not match with defined endpoint
40. UnreachableBrowserExceptionBrowser crashed or couldn’t be opened
41. UnsupportedCommandExceptionDriver received an invalid or unsupported command

Comprehensive Guide to Exception Handling: Handling exceptions properly can prevent unexpected test failures. Selenium supports Java-style exception handling techniques.

✅ 1. Try-Catch Block

Use this to handle known exceptions safely.

java

try {

    WebElement element = driver.findElement(By.id(“login”));

    element.click();

} catch (NoSuchElementException e) {

    System.out.println(“Element not found: ” + e.getMessage());

}


✅ 2. Multiple Catch Blocks

Comprehensive Guide to Exception Handling: Use this when multiple exception types might occur in the same block.

java

try {

    // code

} catch (NoSuchElementException e) {

    // handle element not found

} catch (TimeoutException e) {

    // handle timeout

}


✅ 3. Throw Keyword

Comprehensive Guide to Exception Handling: Throw custom exceptions or propagate an existing one.

java

public void validateElement(WebElement element) throws ElementNotVisibleException {

    if (!element.isDisplayed()) {

        throw new ElementNotVisibleException(“Element not visible”);

    }

}


✅ 4. Throws Clause

Comprehensive Guide to Exception Handling: Declare exceptions in method signature.

java

public void findElement() throws NoSuchElementException {

    WebElement el = driver.findElement(By.id(“test”));

}


✅ 5. Finally Block

Comprehensive Guide to Exception Handling: Code in finally block executes no matter what — ideal for cleanup tasks.

java

try {

    driver.get(“https://example.com”);

} finally {

    driver.quit();

}


  • printStackTrace() – Prints stack trace and detailed error info
  • toString() – Prints a string with the exception type and message
  • getMessage() – Returns only the exception message

Example:

java

try {

    WebElement btn = driver.findElement(By.id(“submit”));

    btn.click();

} catch (NoSuchElementException e) {

    e.printStackTrace();          // Stack trace

    System.out.println(e);        // toString()

    System.out.println(e.getMessage()); // getMessage()

}


  • An exception is a runtime error that disrupts test execution.
  • Selenium throws various types of exceptions depending on the context.
  • You can handle exceptions using try-catch, multiple catches, throw, and finally blocks.
  • Display exception details using printStackTrace, toString, and getMessage methods.

Pro Tip: Always log your exceptions to help in debugging Selenium scripts more efficiently.

Testing Selenium Download

Handle Proxy Authentication

Leave a Comment

Index