Hero Background

Power Your Software Testing with AI Agents and Cloud

The Native AI-Agentic Cloud Platform to Supercharge Quality Engineering. Test Intelligently and Ship Faster.

AutomationSelenium TutorialTutorial

49 Most Common Selenium Exceptions for Automation Testing

Exceptions in Selenium are unavoidable. Here are 49 most common Selenium exceptions which might occur while performing Selenium Test Automation.

Last Updated on:

Selenium exceptions are runtime errors that Selenium WebDriver throws when a command cannot be completed, such as a missing element, a stale element reference, or a closed browser session.

Selenium sorts them into checked exceptions, caught at compile time, and unchecked exceptions such as NoSuchElementException, which appear only at run time.

This guide covers the categories of Selenium exceptions, a cheat sheet of common, Java and C# exceptions, how AI agents triage them now, and how to handle them in Selenium.

Key Takeaways

  • Selenium exceptions are runtime errors thrown by Selenium WebDriver when a command cannot be completed on the target browser.
  • Checked exceptions surface at compile time, while unchecked exceptions such as NoSuchElementException and StaleElementReferenceException surface only during test execution.
  • NoSuchElementException means the locator matched nothing, so the fix is a corrected locator or an explicit wait, not a longer sleep.
  • StaleElementReferenceException means the DOM replaced the element after Selenium stored the reference, so the element must be located again.
  • Selenium Manager resolves browser drivers automatically, which removes the driver-mismatch cause of SessionNotCreatedException.
  • Python uses try and except, while Java and C# use try and catch to handle Selenium exceptions and keep a test suite running.

Introduction To Selenium Exceptions

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.

11 Best Unit Testing Frameworks For Selenium Automation

Key Takeaway: An unhandled Selenium exception stops the test run at that step, so the exception object stack trace is the fastest route to the failing locator or command.

Categories Of Selenium Exceptions

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.

Key Takeaway: Selenium exceptions split into checked exceptions reported at compile time and unchecked exceptions such as NoSuchElementException that appear only at run time.

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.

Watch this video to learn exception handling in Selenium, which covers different types of exceptions and how to handle them using various methods.

Youtube thumbnail

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.

Key Takeaway: The Selenium exception cheat sheet groups exceptions into ones shared by every binding and ones raised only by the Java or C# client library.

Common Selenium Exceptions

Below are some of the common exceptions in Selenium that can happen in all the Selenium WebDriver code.

  • ElementClickInterceptedException
    The Element Click command could not be properly executed as the element that is receiving the Click command was concealed in some way.
  • 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.
  • 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.
  • 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.

  • 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:
    • 401 - Unauthorized
    • 400 - BadRequest
    • 500 - InternalServerError
    • 409 - Conflict
    • 403 - Forbidden
    • 405 - MethodNotAllowed
  • 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.
  • 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.
  • InsecureCertificateException
    The usage of expired or invalid TLS certificates caused the user agent to raise a certificate warning.
  • 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.

  • 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.
  • 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.
  • 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.
  • SessionNotCreatedException
    This exception occurs when the creation of a new session is not successful.
  • 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.

  • 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.
  • 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.

  • 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.

  • 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.

  • 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.
  • 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.
  • JavascriptException
    This exception is thrown when there is an issue in executing JavaScript code.
  • 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.
  • 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.

  • 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.

  • 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.
  • 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.

  • 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:
    • The element could be inside an iFrame which is refreshed.
    • The page may have been refreshed and the element to be accessed is no longer a part of the current page.
    • The element could have been removed and re-added to the screen, since the element was located.

    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.

    Watch this video to learn how to handle Stale Element Reference Exceptions in Selenium with Java.

    Youtube thumbnail
  • 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.

  • 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.

  • 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.
  • UnexpectedTagNameException
    This Selenium exception occurs in cases when a support class is not able to find the expected web element.
  • 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.
  • 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.

Watch the video for detailed insights on how to handle common Selenium Exceptions effectively with practical solutions.

Youtube thumbnail

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:

  • ConnectionClosedException
    This exception is thrown when the connection to the Selenium WebDriver is lost.
  • ErrorHandler.UnknownServerException
    It is used as a placeholder when an error is returned by the server without a stack trace.
  • JsonException
    This exception is thrown when you are able to get the session capabilities where there is no session created.
  • 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.
  • NotFoundException
    This exception occurs when there is no existence of an element on the DOM.
  • ScriptTimeoutException
    It is thrown when the execution of an ASync script does not complete within the given time limit.
  • 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.
  • 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.
  • UnsupportedCommandException
    This exception is thrown when the command sent by the remote Selenium WebDriver is not valid.
  • NoSuchContextException
    This exception occurs in mobile testing and is thrown by ContextAware.context(String).
  • NotConnectedException
    fails after attempting the connection for a stipulated time period.
  • SeleniumException
    As the name suggestions, a Selenium exception is thrown when a Selenium command fails.
  • 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.
  • 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:

  • 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.
  • WebDriverTimeoutException
    The WebDriverTimeoutException class represents exceptions that are thrown when an error occurs when performing actions.
  • XPathLookupException
    Selenium exception that is thrown when an error occurs in the process of an XPath lookup.

Handling Selenium Exceptions

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.

In addition to Selenium exceptions, understanding exception handling in Cypress is also crucial for robust test automation. You can read more about effective exception-handling-in-Cypress techniques in our comprehensive guide.

Also read: Common Challenges In Selenium Automation & How To Fix Them?

Run tests up to 70% faster on the TestMu AI cloud grid

Key Takeaway: Python handles Selenium exceptions with try and except from selenium.common.exceptions, while Java and C# use try and catch with an optional finally block.

How Do AI Agents Handle Selenium Exceptions Now?

AI agents read the exception class, the stack trace and the page source together, then propose a locator or wait fix instead of only reporting a failed step. The engineer still approves the change.

Three shifts changed exception work in Selenium since this guide was first written:

  • Selenium Manager removed a whole exception class.
    Selenium Manager ships inside Selenium 4 and downloads the matching browser driver on its own, so the driver-mismatch form of SessionNotCreatedException and the PATH form of WebDriverException no longer appear in a correctly configured project. Read more on Selenium Manager.
  • Self-healing locators absorb NoSuchElementException.
    A self-healing layer stores several attributes for each element and re-matches on the closest surviving candidate when the primary locator breaks. It suppresses the exception at runtime, so treat every heal as a locator defect to fix in source rather than a pass.
  • Agents generate the handling code.
    An agent given the failing test and the exception message will rewrite a Thread.sleep into a WebDriverWait with the right ExpectedCondition, or re-find an element after a page update to clear StaleElementReferenceException. See AI agent to generate Selenium Java tests.

The limits are real. An agent cannot tell a genuine product bug from a flaky locator, so an ElementClickInterceptedException caused by a broken overlay can be silently retried away. It also cannot fix an ElementNotInteractableException that comes from a disabled control, because the application, not the test, is wrong.

Keep the exception visible in the report even when an agent resolves it. A suite that heals every failure reports green while the locators rot. Pair the agent with stable Selenium locators and explicit waits so the healing layer is a safety net, not the design.

Key Takeaway: AI agents shorten Selenium exception triage by mapping the exception class to a locator or wait fix, but a self-healing pass must still be logged as a locator defect.

All In All

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.

Author

...

Himanshu Sheth

Blogs: 141

  • Twitter
  • Linkedin

Himanshu Sheth is the Director of Marketing (Technical Content) at TestMu AI, with over 8 years of hands-on experience in Selenium, Cypress, and other test automation frameworks. He has authored more than 130 technical blogs for TestMu AI, covering software testing, automation strategy, and CI/CD. At TestMu AI, he leads the technical content efforts across blogs, YouTube, and social media, while closely collaborating with contributors to enhance content quality and product feedback loops. He has done his graduation with a B.E. in Computer Engineering from Mumbai University. Before TestMu AI, Himanshu led engineering teams in embedded software domains at companies like Samsung Research, Motorola, and NXP Semiconductors. He is a core member of DZone and has been a speaker at several unconferences focused on technical writing and software quality.

Add to Google preferred sources

Summarise with AI

Copied to Clipboard!
...

3000+ Browsers. One Platform.

See exactly how your site performs everywhere.

Try it free
...

Write Tests in Plain English with KaneAI

Create, debug, and evolve tests using natural language.

Try for free

Selenium Exceptions FAQs

Did you find this page helpful?

More Related Blogs

TestMu AI forEnterprise

Get access to solutions built on Enterprise
grade security, privacy, & compliance

  • Advanced access controls
  • Advanced data retention rules
  • Advanced Local Testing
  • Premium Support options
  • Early access to beta features
  • Private Slack Channel
  • Unlimited Manual Accessibility DevTools Tests