
🏹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:
- What is an Exception?
- Types of Exceptions in Selenium
- Exception Handling Techniques in Selenium
- Exception Display Methods
- Summary
🏹 Types of Exceptions in Selenium WebDriver
Comprehensive Guide to Exception Handling: Below is a list of the most commonly encountered exceptions in Selenium:
Exception Name | Description |
1. ElementNotVisibleException | The element exists in the DOM but is hidden |
2. ElementNotSelectableException | The element is present but not selectable |
3. NoSuchElementException | The element could not be found in the DOM |
4. NoSuchFrameException | The target frame does not exist |
5. NoAlertPresentException | No alert is present to switch to |
6. NoSuchWindowException | The target window does not exist |
7. StaleElementReferenceException | The element is detached from the current DOM |
8. SessionNotFoundException | WebDriver is still acting after the session was quit |
9. TimeoutException | Command did not finish in the expected time |
10. WebDriverException | Generic WebDriver error after closing the browser |
11. ConnectionClosedException | Driver disconnection occurred |
12. ElementClickInterceptedException | Another element is blocking the clickable one |
13. ElementNotInteractableException | Element cannot be interacted with |
14. ErrorInResponseException | Issue while communicating with Firefox extension |
15. UnknownServerException | Server returns an error without a stack trace |
16. ImeActivationFailedException | IME engine activation failed |
17. ImeNotAvailableException | IME support not available |
18. InsecureCertificateException | Certificate issue like expired or invalid SSL |
19. InvalidArgumentException | Argument type is not as expected |
20. InvalidCookieDomainException | Cookie set for an invalid domain |
21. InvalidCoordinatesException | Invalid coordinates provided for interaction |
22. InvalidElementStateException | Element is in a state that cannot be interacted with |
23. InvalidSessionIdException | Session ID is invalid or inactive |
24. InvalidSwitchToTargetException | Target window/frame does not exist |
25. JavascriptException | JavaScript execution failed |
26. JsonException | Session not created or returned invalid JSON |
27. NoSuchAttributeException | Attribute not found in the element |
28. MoveTargetOutOfBoundsException | Target is out of screen/document bounds |
29. NoSuchContextException | Used in mobile testing contexts |
30. NoSuchCookieException | Cookie with the given path does not exist |
31. NotFoundException | Element not found on the DOM |
32. RemoteDriverServerException | Server fails due to improper capability definitions |
33. ScreenshotException | Unable to take screenshot |
34. SessionNotCreatedException | Session could not be created |
35. UnableToSetCookieException | Failed to set cookie in driver |
36. UnexpectedTagNameException | Incorrect tag name used for element |
37. UnhandledAlertException | Alert appears but not handled properly |
38. UnexpectedAlertPresentException | Unexpected alert appeared |
39. UnknownMethodException | Method does not match with defined endpoint |
40. UnreachableBrowserException | Browser crashed or couldn’t be opened |
41. UnsupportedCommandException | Driver received an invalid or unsupported command |
🏹How to Handle Exceptions in Selenium WebDriver
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();
}
🏹 Methods for Displaying Exception Info
- 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()
}
🏹 Summary
- 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.