A developer will always write code keeping different scenarios in mind but there could be cases where the implementation does not work as expected. The same principle also applies to test code that is primarily written to test the existing product functionalities, unearth bugs, and make the product 100% bug free.
It is rightly said that Truth is always stranger than fiction and you would witness a lot of ‘stranger things’ when you perform Selenium test automation. These things or scenarios that you encounter when executing your test code may not be very common but the test implementation should be robust enough to handle such scenarios. These scenarios are aptly termed as exceptions and you would come across many such exceptions when using Selenium for automated browser testing.
Selenium exceptions are extensively used for handling error scenarios and avoiding web application failures. Though there are many Selenium exceptions that may happen in all the Selenium WebDriver code, some Selenium exceptions are specific to the programming languages supported by the framework e.g. Java, C#, Python, etc. This blog covers common Selenium exceptions as well as language specific exceptions, an exhaustive list that can be helpful when you encounter exceptions in your code.
By the end of this blog, you would have a complete picture about the frequently used Selenium exceptions when executing automated browser testing related scenarios.
An exception (also referred as fault) is an unprecedented event that occurs during the process of program execution. When an exception occurs, normal program execution halts and the corresponding exception handler is executed. If there is no exception handler to handle that particular exception, the program will return to the calling function that threw the exception eventually leading to termination of the program.
As Selenium test automation is performed on different target platforms, devices, and web browsers; the behavior of the test code can vary depending on the browser type or browser version. For example, some attributes may be browser specific and an exception is thrown if the particular attribute is not present in the browser on which automated browser testing is performed. Common property names can also be browser specific which can lead to Selenium exceptions like NoSuchAttributeException if the same property is not present on the target browser.
Proper handling of exceptions is a good practice as unhandled exceptions can lead to program failure that eventually hampers the product experience. The exception object contains information regarding the type of exception, call stack, and other useful information that will be helpful for debugging & making the code more foolproof.
There are two broad categories of Selenium exceptions – Checked exceptions and Unchecked exceptions. These exceptions are classified based on the time when the exceptions are caught i.e. compile time or runtime.
A. Checked Exceptions
Checked exceptions in Selenium test automation are handled during the process of test code implementation e.g. NoSuchAttributeException, etc. The handling of checked exceptions occurs during the compile time itself.
If some method is throwing a checked exception, it is better to define a handler that handles that particular exception.
B. Unchecked Exceptions
Unchecked exceptions in Selenium test automation occur during runtime and can have severe repercussions than checked exceptions. e.g. ElementNotVisibleException, MoveTargetOutOfBoundsException, etc.
Exceptions in Java can be checked or unchecked whereas in C++, all exceptions are unchecked. Unchecked exceptions are commonly encountered in automated browser testing related scenarios as the tests span across different combinations and versions of web browsers and operating systems.
Selenium Exceptions Cheat Sheet
When performing automated browser testing on a local or remote Selenium grid, you would come across different types of exceptions. Some Selenium exceptions are specific to the programming language used for writing Selenium test automation scenarios.
Common Selenium Exceptions
Below are some of the common Selenium exceptions that can happen in all the Selenium WebDriver code.
1. ElementClickInterceptedException
The Element Click command could not be properly executed as the element that is receiving the Click command was concealed in some way.
2. ElementNotInteractableException
This ‘ElementNotInteractableException’ Selenium exception is thrown when even though the targeted web element exists on the DOM, interactions with that element will hit another web element.
3. ElementNotSelectableException
This Selenium Exception occurs when the target element is present on the DOM but it cannot be interacted with as the element is not selectable. For example, this exception will be thrown when interacting with the script element.
4. ElementNotVisibleException
The most common type of Selenium exception, that is thrown when even though the web element is present but it is not visible. As the element is not visible, any interaction with the element is not possible.
This scenario is commonly encountered in Selenium test automation where relevant operation (click, read, etc.) on the web element e.g. button, label, etc. is attempted but the element is hidden from the view. Another example is elements defined in HTML that have type hidden.
5. ErrorInResponseException
This Selenium exception is thrown when some issue or error has occurred on the server side. It could happen when the wrong combination of username & access key is used to access a cloud based remote Selenium Grid, communicating with a remote Web Driver server, or communicating with a Firefox extension (or Chrome add-on).
Some of the common response codes for server-side errors are:
6. ImeActivationFailedException
This exception is thrown if the activation of IME (Input Method Engine) has failed for some reason.
The ideal manner to handle this is by checking if there is IME support available on the machine.
7. ImeNotAvailableException
This Selenium exception is thrown if IME (Input Method Engine) is not available. ImeNotAvailableException is thrown for every IME-related method in cases where there is IME support that is not available on the test machine.
8. InsecureCertificateException
The usage of expired or invalid TLS certificates caused the user agent to raise a certificate warning.
9. NoSuchFrameException
The NoSuchFrameException Selenium exception is thrown when the frame to be switched-to does not exist.
To avoid such Selenium exceptions, it is recommended to add a sanity check in the automated browser testing code regarding the mode of switching to the frame. Check if the frame index being used is proper. An additional wait of a few milliseconds (ms) can be added to ensure that the loading of the frame is complete.
10. NoSuchWindowException
This exception is thrown when the window target being switched-to does not exist. These scenarios can be taken care of by using window_handles in order to get the current set of active windows. Window handles can be used to perform appropriate actions on the same.
11. RemoteDriverServerException
This exception is thrown when incorrect combinations/fields in browser capabilities leads to the server not sending a response. To avoid such Selenium Exceptions, it is important that the Selenium browser capabilities are thoroughly checked from the viewpoint of valid combinations of (platform + browser), (platform + browser + browser version), etc.
12. ScreenshotException
As the name implies, this Selenium exception is thrown when the screen capture is not possible.Such a scenario is likely in web pages/web apps where sensitive information e.g. username, password, banking information, etc. is entered by the user. In such cases, screenshot can’t be captured due to the screenshot restriction on Here, screenshot restriction prevents the screen from being captured or recorded.
13. SessionNotCreatedException
This exception occurs when the creation of a new session is not successful.
14. InvalidArgumentException
The InvalidArgumentException exception is thrown when the arguments being passed are either invalid or malformed.
A better practice is to verify that the web page under test is loaded using appropriate wait (in ms) in the Selenium test automation code.
15. InvalidCookieDomainException
This Selenium exception is thrown when an attempt to add a cookie is for a different URL/domain than the current URL. To handle this exception, you should navigate to the correct URL where the cookie has to be added.
16. InvalidCoordinatesException
This particular exception is thrown when incorrect coordinates are offered to an interactions operation.
This also means that an action that is dependent on a mouse position (e.g. click) was not preceded by a move operation or the move operation was provided with invalid coordinates.
17. InvalidElementStateException
This Selenium exception is thrown when a command cannot be completed as the element is not in a valid state or the element is not enabled to perform that action. It can be caused if an operation like clearing an element is attempted on a web element that is non-editable and non-resettable.
To handle such an exception in Selenium test automation, it is recommended to wait for that element to be enabled before the desired action is performed on it.
18. InvalidSelectorException
The usage of invalid or incorrect selectors for locating web elements can occur accidentally if the selector name is changed between different releases. The InvalidSelectorException is thrown if the selector being used to find a web element does not return a WebElement.
This commonly happens when an XPath expression is the selector and the XPath is not valid. This results in failure to locate the intended web element.
19. InvalidSessionIdException
This exception is thrown if the session id being used in Selenium test automation implementation is invalid i.e. it is not in the list of currently active sessions. This can occur if the session is either not active or it never existed.
20. InvalidSwitchToTargetException
This Selenium exception appears if the frame or window target being switched to is invalid.It is important to verify the XPath of the target frame using ‘Inspect tool’ before switching to that frame.
21. JavascriptException
This exception is thrown when there is an issue in executing JavaScript code.
22. NoAlertPresentException
It occurs when switching to an alert that is not yet present on the screen. The ideal way to handle alerts is to check whether the alert is present, post which the desired operation on the Alert() class should be called.
23. MoveTargetOutOfBoundsException
This Selenium exception is thrown if the target being provided to the ActionChains() move method is out of bounds i.e. invalid or outside the document/web page.
Before calling the move method of ActionChains() class, you should always check the location we are trying to move and execute the same only if the location is present on the screen.
24. NoSuchAttributeException
This is one of the few Selenium exceptions that you would definitely come across when doing automated browser testing. The NoSuchAttributeException is thrown if the attribute of the element could not be located.
To handle this exception, the existence of the attribute should be checked for the browser on which testing is performed. Different property names for the same property can vary from one browser to another and inefficient handling could lead to this exception.
Another way to avoid the occurrence of this exception is by changing the attribute based on the new details of the element on the DOM.
25. NoSuchCookieException
This Selenium exception occurs in cases when cookie matching a given pathname is not present in the associated cookies of the current browsing context’s active document.
26. NoSuchElementException
The NoSuchElementException is thrown when the locator being used to access the element is invalid or an attempt is made to perform action on an element which is not on the DOM. In either of the cases, the element would not be found.
To handle this Selenium exception, you should check whether the selector is correct and if it is correct, have an additional wait to ensure the appearance of the WebElement.
27. StaleElementReferenceException
This Selenium exception occurs when a reference to an element is made that is not anymore on the DOM of the page. In simple words, the element is decayed or stale.
Some of the possible reasons for this particular Selenium exception are:
A possible solution to handle this exception is to use dynamic XPath to find the required element in a loop and break the loop once the element is located.
28. TimeoutException
The TimeoutException occurs when the command that is currently in execution does not complete within the expected time frame.
A possible solution to handle this exception is increasing the wait time for the command to complete execution. However, an idealistic value should be chosen for the wait time else further execution can get delayed.
29. UnableToSetCookieException
This Selenium exception occurs in the cases where the Selenium WebDriver is unable to set a cookie.
An additional wait can be added so that the cookie is loaded for the domain.
30. UnexpectedAlertPresentException
It occurs when an unexpected alert appears. A common reason for the occurrence of this exception is blocking of Selenium WebDriver commands caused by the appearance of modal windows/pop-ups on the page.
31. UnexpectedTagNameException
This Selenium exception occurs in cases when a support class is not able to find the expected web element.
32. UnknownMethodException
This is one of the common Selenium exceptions that occur when the requested command is able to match a known URL but unable to match the method for that URL.
To handle this exception, you should check whether the method being passed along with the URL is valid or not.
33. WebDriverException
This is the base WebDriver exception that occurs due to incompatibility in the binding of Selenium WebDriver and target web browser.
To handle this exception, you should download the Selenium WebDriver library that is compatible with the corresponding web browser.
Selenium Exceptions In Java
Some Selenium exceptions are specific to a particular programming language for test automation. Along with the common exceptions in Selenium that were covered in the previous section, below are Selenium exceptions specific to the Java Language:
34. ConnectionClosedException
This exception is thrown when the connection to the Selenium WebDriver is lost.
35. ErrorHandler.UnknownServerException
It is used as a placeholder when an error is returned by the server without a stack trace.
36. JsonException
This exception is thrown when you are able to get the session capabilities where there is no session created.
37. NoSuchSessionException
This Selenium exception is thrown when a command is called after the WebDriver.quit() is executed. As the WebDriver instance no longer exists, any operation on that particular WebDriver instance returns this exception.
38. NotFoundException
This exception occurs when there is no existence of an element on the DOM.
39. ScriptTimeoutException
It is thrown when the execution of an ASync script does not complete within the given time limit.
40. UnhandledAlertException
This Selenium exception is a subclass of WebDriver exception. It is thrown when the WebDriver is unable to perform the Alert operation even when there is an Alert.
41. UnreachableBrowserException
The UnreachableBrowserException indicates that there is a problem communicating with the web browser that is being controlled by the automation test code. It could also be due to issues in communicating with the Selenium server.
It can occur if the server address to the remote Selenium WebDriver or Selenium grid is not valid. There is also a possibility that the browser instance has died in the midst of the Selenium test automation cycle.
42. UnsupportedCommandException
This exception is thrown when the command sent by the remote Selenium WebDriver is not valid.
43. NoSuchContextException
This exception occurs in mobile testing and is thrown by ContextAware.context(String)
44. NotConnectedException
This Selenium exception is thrown when the attempt to a particular host or remote Selenium grid fails after attempting the connection for a stipulated time period.
45. SeleniumException
As the name suggestions, a Selenium exception is thrown when a Selenium command fails.
46. UnableToCreateProfileException
The UnableToCreateProfileException occurs when the browser on which Selenium test automation is to be performed is opened with some custom profile but the WebDriver or browser has issues in supporting that profile.
To handle this exception, it is recommended to check the profiles supported by the installed version of Selenium WebDriver as well as the web browser.
47. UrlChecker.TimeoutException
This exception is thrown when the browser is unable to open the URL under test after trying for a certain duration.
To handle this Selenium exception, the URL has to be checked for its correctness before an attempt is made to open in the browser (under test).
Selenium Exceptions In C#
The Selenium exceptions that are specific to C# are:
48. DriverServiceNotFoundException
The exceptions under the DriverServiceNotFoundException class are thrown when an element on which the automated browser testing is performed is not visible.
To handle this exception, you can wait for the page to be completely loaded and execute the Selenium WebDriver command only after confirming the presence visibility of the Web Element.
49. WebDriverTimeoutException
The WebDriverTimeoutException class represents exceptions that are thrown when an error occurs when performing actions.
Bonus Point, here we are giving a Ryme number
50. XPathLookupException
Selenium exception that is thrown when an error occurs in the process of an XPath lookup.
The ways in which Selenium exceptions are handled differ from one programming language to another. However, the bottom line is that Selenium exceptions should be handled as the exception provides extremely critical information.
Below is the short gist on how Selenium exceptions are handled in popular programming languages:
Python – If you are using Python for automated browser testing, the exception classes are available in selenium.common.exceptions which should be imported before using any commands from that package.
Exceptions are handled using try…except block where the try block enables you to test the code for errors, the except block helps you handle the error, and the optional finally block will be executed irrespective of whether the try block raises an error or not.
Java – Selenium exceptions are handled in Java using the try-catch method. The try block is the start of the block and the catch block contains the implementation to resolve the exception. The catch block is placed at the end of the try block. Like Python, you can also make use of the finally keyword to create a block of code that is executed whether exception occurs or not.
C# – Like Java, Selenium exceptions are handled using the try-catch statement. The try block contains code that may cause the exception. The code under the try block is executed until the code is successfully executed or an exception is thrown. The catch block contains the handlers for different exceptions.
Exceptions are quite common in development but they have to be handled carefully. It is important to know about the different Selenium exceptions as that helps in development of a more robust automated browser testing scripts.
Exception handling in Selenium test automation is instrumental in identifying cross browser compatibility issues pertaining specific to browser/platform/device.
What are some of the mechanisms that you have used to handle Selenium exceptions, do leave your experience in the comments section… Happy Testing ☺
Previously published at https://www.lambdatest.com/blog/49-common-selenium-exceptions-automation-testing/