DEV Community

Cover image for Common Exceptions in Selenium & How to Handle Them
Steve Wortham
Steve Wortham

Posted on

Common Exceptions in Selenium & How to Handle Them

While executing an automated test scripts, testers and developers often come across scenarios where test script fails abruptly due to exceptions like element not being found, invalid json, or element not visible, and many more causing the entire test suite to halt. Test executions can even be hindered by intermittent network connectivity issues. These are just a few examples of how exceptions can disrupt any testing process. By understanding how to handle these exceptions effectively, you can prevent such roadblocks and ensure the smooth execution of your test scripts.

Selenium is a powerful tool for test automation and is responsible for ensuring the quality and reliability of web applications. However, like any software, it is also prone to exceptions that can disrupt test execution. These exceptions can arise due to various reasons, such as element unavailability, network issues, or unexpected page behavior.

To build robust and maintainable Selenium test scripts, it’s crucial to gracefully handle these exceptions. By implementing effective exception handling mechanisms, you can prevent test failures, improve test reliability, and gain valuable insights into potential issues in your application.

This blog will delve into common Selenium exceptions, exploring their causes, and providing practical solutions to mitigate their impact. By mastering exception handling, you can elevate your Selenium testing capabilities and create more resilient automation suites.

What is Exception in Selenium?

An uncommon or unprecedented event that takes place while a software program or application is being executed is referred to as an exception. It is a runtime error caused by an unforeseen outcome or occurrence that affects and ruins regular program flow. An exception is seen as a flaw as well.

When an automation tester or developer writes or executes a Selenium script, the test can be impacted by unforeseen issues in the code, known as exception in Selenium.

When an exception is encountered, an exception object is created containing debugging information like the line number, the type of exception, and the method hierarchy. Once this exception object is generated and passed to the runtime environment, the process is called “throwing the exception.”

Types of Exception in Selenium

In Selenium, exceptions are mainly categorized into two types:

1. Checked Exceptions

Checked exceptions are anticipated errors that the compiler forces you to acknowledge and handle. These exceptions typically arise from external factors or resource constraints. A classic example is attempting to locate an element that is not present on the page. The compiler mandates that you either handle this exception using a try-catch block or declare it in the method signature. This approach promotes robust code by compelling developers to consider potential issues beforehand.

2. Unchecked Exceptions

Unlike checked exceptions, unchecked exceptions are not anticipated by the compiler and can occur at runtime. These exceptions often stem from programming errors or unexpected application behavior. Examples include attempting to access an element that has become stale due to page changes or encountering a NullPointerException when working with object references. While it’s advisable to handle these exceptions to enhance code reliability, the compiler doesn’t enforce their handling, allowing for more flexibility in code structure.

List of 33 Common Selenium Exceptions

Selenium provides a list of predefined exceptions to help analyze and debug tests more efficiently. Here are some common Selenium exception lists explained in detail:

  1. WebDriverException: This occurs when an action is attempted while the WebDriver connection is closed. It indicates that the WebDriver cannot interact with the browser because the session has ended.
  2. TimeOutException: This exception is thrown when a command exceeds the specified or default wait time. It typically occurs when waiting for an element or operation to complete but it takes too long.
  3. ElementNotVisibleException: This occurs when Selenium tries to locate an element (using locators in Selenium), but the element is not visible on the page. It means the element exists in the DOM but is hidden from view.
  4. NoSuchWindowException: This happens when Selenium tries to switch to a window that does not exist. It indicates that the target window cannot be found.
  5. NoSuchElementException: This exception is thrown when Selenium cannot find an element on the web page. It occurs when the element does not exist at all, unlike the ElementNotVisibleException, which occurs when the element exists but is hidden.
  6. ElementNotInteractableException: This occurs when an element is present in the DOM but cannot be interacted with. This might be due to overlapping elements or attempting to interact with the element before it is ready.
  7. ConnectionClosedException: This exception occurs when the connection to the Selenium driver is unexpectedly closed, preventing further interaction with the browser.
  8. ElementClickInterceptedException: This happens when an element intercepts the click intended for another element, preventing the action from being completed.
  9. ElementNotSelectableException: This is thrown when an element exists in the DOM but cannot be selected. The WebDriver is unable to interact with the element due to its state.
  10. ErrorHandler.UnknownServerException: This exception is used as a placeholder when a server returns an error without providing a stack trace. It signifies that an unknown server-side error occurred, and there is insufficient information to diagnose the issue.
  11. ErrorInResponseException: This exception typically originates from server-side errors. It indicates that the server responded with an error, which the Selenium client was unable to handle properly.
  12. ImeActivationFailedException: This occurs when the Input Method Engine (IME), used for inputting multi-byte characters like Chinese or Japanese, fails to activate. It indicates that the system could not switch to the desired input method.
  13. ImeNotAvailableException: Similar to the ImeActivationFailedException, this occurs when IME support is unavailable. It means that the required Input Method Engine (IME) is not available on the system, preventing the input of multi-byte characters.
  14. InsecureCertificateException: This happens when navigating to a webpage with an expired or invalid TLS certificate. It indicates that the browser detected a security issue with the site’s certificate, such as it being expired or not being trusted.
  15. InvalidArgumentException: This is thrown when a specified argument type does not match any expected type. It occurs when the input provided to a method or function is not of the correct type or format.
  16. InvalidCookieDomainException: This exception occurs when trying to add a cookie for an invalid URL or domain. It indicates that the domain specified for the cookie is not valid, possibly due to a typo or incorrect domain structure.
  17. InvalidCoordinatesException: This self-explanatory exception occurs when invalid coordinates are specified for an operation. It typically happens when trying to perform actions that require specific screen coordinates, such as clicking or dragging.
  18. InvalidSessionIdException: This is thrown when the session ID is invalid because the session is inactive or has been terminated. It means that the WebDriver session being referenced no longer exists.
  19. InvalidElementStateException: This exception occurs when Selenium cannot complete a command on a specified element due to its current state. For example, trying to click a disabled button or interact with a read-only field.
  20. JavascriptException: This exception is thrown when the provided JavaScript code cannot be executed or is incorrect. It indicates that there was an error in the script provided to the WebDriver for execution.
  21. InvalidSwitchToTargetException: This occurs when switching to different tabs, windows, or frames with incorrect arguments. It indicates that the specified target for the switch operation does not exist or is not accessible.
  22. JsonException: This happens when the Selenium client cannot parse the returned values from an action or operation. It indicates that the response from the server or browser could not be properly converted into a usable format due to incorrect or malformed JSON.
  23. MoveTargetOutOfBoundsException: This occurs when the WebDriver tries to access an element outside the viewport. This can be mitigated by scrolling the element into view. 24.** NoAlertPresentException:** This exception is thrown when the code written to handle an alert cannot find the alert during execution. It typically occurs when you attempt to switch to or interact with an alert that is not currently present on the web page.
  24. NoSuchAttributeException: This exception occurs when Selenium tries to access an attribute of an element that does not exist. For example, if you try to get the value of a non-existent attribute, this exception will be thrown.
  25. NoSuchContextException: Typically encountered during mobile device testing, this exception is thrown when the context you are trying to switch to cannot be found. Contexts in mobile testing can refer to different views such as native app views and web views.
  26. NoSuchCookieException: This exception is thrown when Selenium cannot find a specified cookie. It occurs when you attempt to retrieve or delete a cookie that does not exist in the browser’s cookie store.
  27. NoSuchFrameException: This occurs when Selenium cannot find the target iframe. It typically happens when you try to switch to a frame that does not exist in the DOM. This can occur if the frame ID or name is incorrect or if the frame has not been loaded yet.
  28. RemoteDriverServerException: This exception occurs when the Selenium server does not respond due to improperly described capabilities. It indicates a problem with the configuration or setup of the WebDriver, leading to a failure in communication with the server.
  29. UnsupportedCommandException: This occurs when the remote WebDriver sends commands that are invalid or not supported. It indicates that the command being attempted is not recognized by the WebDriver or the browser being used.
  30. StaleElementReferenceException: This exception is thrown when you try to interact with a DOM element that is no longer attached to the DOM tree. This can happen if the element has been removed or the page has been refreshed or updated, making the reference to the element outdated.
  31. SessionNotFoundException: This occurs when an action is performed without an active WebDriver session or if the session has been terminated. It indicates that the WebDriver session you are trying to use no longer exists, possibly due to a browser crash or manual session termination.
  32. SessionNotCreatedException: This exception is thrown when the WebDriver cannot create a new session. It can happen due to various reasons such as incorrect WebDriver configuration, incompatible browser version, or issues with the WebDriver binary itself.

What is Exception Handling in Selenium?

Exception handling in Selenium involves the process of detecting and managing errors that occur during the execution of test scripts. When an unforeseen event or error disrupts the normal flow of a Selenium script, exception handling mechanisms allow developers to manage these disruptions gracefully. This ensures that the test execution does not abruptly stop, and appropriate actions can be taken to address or log the issues. Proper exception handling helps in creating resilient and reliable automation tests by enabling the scripts to handle unexpected situations effectively and continue running or provide meaningful feedback.

If an exception is not handled appropriately, the rest of your tests may also fail. The inability to differentiate between an application problem and a Selenium problem due to the Exception in Selenium complicates the interpretation of automation results.

Different Methods to Handle Exception In Selenium

Exception handling in Selenium WebDriver involves various techniques to manage errors and ensure smooth execution of test scripts. Here are some standard methods for handling exceptions in Selenium WebDriver:

1. Try-Catch

The try-catch construct is the foundational method for handling exceptions. The try block contains the code that might throw an exception, while the catch block handles the exception if one occurs. This method allows you to protect sections of code that might fail and handle errors gracefully.

Syntax:

try {
// Code that might throw an exception
} catch (Exception e) {
// Code to handle the exception
}

2. Multiple Catch Blocks

When dealing with various types of exceptions that might arise from a single block of code, you can use multiple catch blocks. Each catch block can handle a specific type of exception, allowing for more precise error management. You can have as many catch blocks as needed.

Syntax:

try {
// Code that might throw exceptions
} catch (ExceptionType1 e1) {
// Handle ExceptionType1
} catch (ExceptionType2 e2) {
// Handle ExceptionType2
}

3. Throw / Throws

Throw: The throw keyword is used to explicitly throw an exception from within a method. This is useful when you want to pass an exception to the calling method for handling.

Syntax:

public static void anyFunction() throws Exception {
try {
// Code that might throw an exception
} catch (Exception e) {
// Handle the exception
throw e; // Re-throw the exception
}
}
Throws: The throws keyword is used in a method signature to indicate that the method might throw specific exceptions. It informs the caller of the method about potential exceptions that need to be handled.

Syntax:

public static void anyFunction() throws ExceptionType1, ExceptionType2 {
// Method code
}

4. Finally

The finally block is used to execute code that should run regardless of whether an exception was thrown or not. This is useful for cleanup operations, such as closing files or releasing resources.

Syntax:

try {
// Code that might throw an exception
} catch (ExceptionType1 e1) {
// Handle ExceptionType1
} catch (ExceptionType2 e2) {
// Handle ExceptionType2
} finally {
// Code that always executes
}

5. Exception Information Methods

To get detailed information about exceptions, you can use the following methods:

printStackTrace(): Prints the stack trace of the exception, including the exception name and a description, which helps in debugging.
toString(): Returns a string representation of the exception, including its name and description.
getMessage(): Retrieves the description of the exception, providing more context about what went wrong.
By using these techniques, you can effectively manage exceptions in Selenium WebDriver, ensuring that your test scripts handle errors gracefully and provide meaningful feedback.

Exception Handling Best Practices

Effective exception handling is key to developing robust and reliable automation tests. Here are some best practices to follow:

  • Handle Common Conditions Without Throwing Exceptions: Anticipate and address common conditions or errors in your code without relying on exceptions. This helps prevent unnecessary exception handling and keeps your code cleaner.
  • Design Classes or Methods to Avoid Exceptions: Structure your classes and methods to minimize the likelihood of exceptions. Proper design and validation checks can prevent errors from occurring in the first place.
  • Predict Exceptions and Use Try/Catch/Finally Blocks: Anticipate potential exceptions and include try-catch-finally blocks in your code to handle them gracefully. This ensures that your program can manage errors effectively and continue running.
  • Write Meaningful Error Messages: Provide clear and informative error messages in your catch blocks. This helps in diagnosing the problem quickly and understanding the context of the error.
  • Create Custom Exceptions When Needed: Define custom exceptions to make error handling more readable and specific to your application’s needs. Custom exceptions can provide more meaningful error messages and enhance code clarity.
  • Catch Specific Exception Types: Avoid using generic Exception in catch blocks. Instead, catch specific exceptions like ArithmeticException to handle different error scenarios more precisely.
  • Use Proper Naming Conventions for Custom Exceptions: Follow consistent naming conventions when creating custom exceptions. This improves code readability and helps in identifying the purpose of the exception easily.
  • Differentiate Between Test Case Errors and Coding Errors: Distinguish between errors that occur due to test case failures (e.g., assertion errors) and those caused by coding issues. This helps in isolating and addressing problems more effectively.
  • Use the Finally Block for Resource Cleanup: Ensure that resources such as file handles or database connections are properly closed using the finally block. This guarantees that resources are released regardless of whether an exception was thrown.

Conclusion

Exceptions in Selenium and handling them is a critical component of every Selenium script, as it ensures that the tests run smoothly even when unexpected errors occur. Ignoring exceptions can lead to disruptions in the normal execution of programs, making robust exception handling essential for maintaining the reliability of automated tests.

Source: This article was originally published at testgrid.io.

Top comments (0)