Testsigma

Products

Solutions

Resources

DocsPricing
left-mobile-bg

Common Exceptions in Selenium | How to handle Selenium Exceptions

April 25, 2025
right-mobile-bg
Common Exceptions in Selenium | How to handle Selenium Exceptions
image

Start automating your tests 10X Faster in Simple English with Testsigma

Try for free

Though test automation seems easy, it has many challenges, such as maintaining a stable environment and designing and maintaining robust automation frameworks. Exception handling and error reporting are key areas to consider while designing the automation framework. Every automation tool and programming language has its own way of exception handling. Let’s discuss the exceptions and exception handling in Selenium.

What are Exceptions in Selenium?

Exceptions in Selenium are problems that stop the program from running normally. They show that something went wrong. We use them to handle errors and make automation scripts stronger.

The exceptions can be broadly classified into two types: Checked exceptions and Unchecked exceptions.

  • Checked Exceptions: These types of exceptions occur while writing the code. These exceptions need to be analyzed and fixed before compilation, else the compiler will throw the exception. Most of the advanced IDEs highlight compilation errors while writing the code.
  • Unchecked Exceptions: The errors or exceptions that occur during runtime are called Unchecked exceptions. The Unchecked exceptions require careful analysis and debugging as they are thrown during the execution. Though IDEs provide debugging features, it doesn’t highlight such issues while writing the code.

List of Exceptions in Selenium

Selenium has some predefined exception lists that help analyze and debug the Selenium tests easily. Let’s understand some of the common Selenium exceptions in detail:

  • WebDriverException: The WebDriverException occurs when it tries to perform an action when the WebDriver connection is in a closed state.
  • TimeOutException: TimeOutException occurs when a command takes more time than the specified or default wait time.
  • ElementNotVisibleException: Selenium tries to find the element based on the values provided, such as XPath, CSS, ID, etc. If the element state is hidden, then the ElementNotVisibleException is thrown.
  • NoSuchWindowException: The NoSuchWindowException occurs when the target window to be switched to doesn’t exist.
  • NoSuchElementException: The exception occurs when Selenium cannot find the element. The NoSuchElementException and ElementNotVisibleException are very similar. The NoSuchElementException is thrown when the element doesn’t exist at all on the webpage. The ElementNotVisibleException is thrown when an element exists, but it is hidden so the WebDriver cannot find and interact with it.
  • ElementNotInteractableException: This exception is thrown when an element is present in the DOM Tree but is impossible to interact with. There may be various reasons, such as an element might be overlapped with another element, or performing interactions before it is ready to take an event etc.
  • ConnectionClosedException: This exception occurs when the connection to the Selenium driver is closed.
  • ElementClickInterceptedException: The command could not be completed as the element receiving the events is concealing the element that was requested to be clicked.
  • ElementNotSelectableException: Thrown when an element exists in the DOM but is unavailable for selection, so the WebDriver cannot interact with the element.
  • ErrorHandler.UnknownServerException: If a server returns an error without any stack trace, then this exception can be used as a placeholder
  • ErrorInResponseException: This exception typically originates from the server side.
  • ImeActivationFailedException: The IME stands for Input Method Engine, typically used when inputting Chinese/Japanese or multi-byte characters. So the ImeActivationFailedException happens when the IME Engine cannot be activated.
  • ImeNotAvailableException: Similar to the above exception, it occurs when the IME support is not available.
  • InsecureCertificateException: The webpage uses the TLS certificate for authenticity. When your webpage has an expired or invalid TLS certificate and you are trying to navigate, then the InsecureCertificateException is thrown.
  • InvalidArgumentException: Thrown when a specified argument type does not belong to any exception type.
  • InvalidCookieDomainException: If you are trying to add the cookie for an invalid URL or domain, then this exception is thrown
  • InvalidCoordinatesException: This exception is self-explanatory and happens when you specify invalid coordinates to perform a specific operation.
  • InvalidSessionIdException: If the session isn’t active or the session is terminated, then Selenium considers the session ID invalid and throws the InvalidSessionIdException.
  • InvalidElementStateException: When Selenium cannot complete the command on a specified element, then the InvalidElementStateException is thrown
  • JavascriptException: Typically thrown if the JavaScript code provided by the user cannot be executed or if the supplied script is wrong.
  • InvalidSwitchToTargetException: Selenium allows you to switch to different tabs, windows, or frames. If you specify the wrong arguments, then Selenium throws this exception.
  • JsonException: The JsonException occurs when any action/operation returns values that cannot able to parsed by the Selenium client.
  • MoveTargetOutOfBoundsException: Occurs when the element that Selenium WebDriver is trying to access is not within the viewport. To suppress this exception, one can try scrolling or other actions to bring the element to the viewport.
  • NoAlertPresentException: If you have written the code to handle the alert, but during the execution, if it can’t find the alert to switch, then this exception will be thrown.
  • NoSuchAttributeException: If you are trying to access the element with an attribute, however, due to various reasons, that attribute is not available, this exception is raised.
  • NoSuchContextException: Typically thrown while performing mobile device testing.
  • NoSuchCookieException: If Selenium cannot match the cookie in the user-specified path, then this exception is thrown.
  • NoSuchFrameException: When Selenium cannot find the target iframe, it throws the NoSuchFrameException
  • RemoteDriverServerException: When the server doesn’t respond thanks to the fact that the capabilities described aren’t proper
  • UnsupportedCommandException: This exception occurs when the remote WebDriver sends invalid commands.
  • StaleElementReferenceException: Occurs if you are trying to access the DOM element that is detached from the DOM tree.
  • SessionNotFoundException: If you act when there is no active WebDriver session or if it has just terminated, then this exception happens.
  • SessionNotCreatedException: When WebDriver cannot create a new session, it throws the SessionNotCreatedException.

Handling Exceptions in Selenium

Exceptions are quite common in Selenium; if it is not handled properly, then the automation tests can give you false failures or wrong results.

If an exception is not handled as expected, your subsequent tests might also fail. The Exception in Selenium makes it difficult to distinguish between the application problem and the Selenium problem; hence, the interpretation of automation results will become complicated.

Selenium or underlying programming languages provide a different way to handle the exceptions gracefully and provide custom messages and stack traces as and when such exceptions occur.

Why Exception Handling is Important

  • Easy to identify the error with custom messages and stack traces
  • Makes the program run smoothly even after the exception is thrown.
  • Helps to identify the root cause of the problem.
  • Helps in meaningful error reporting.
  • Easy to identify the error types.

Common Reason for Exceptions

The exception may occur for multiple reasons. Below are some common reasons:

  • Invalid user input/passing arguments
  • Memory issues
  • Device failure
  • Network-related problems
  • Error in the code
  • Problem with the file or file format while opening the file

Exception Categories

At the top level, the exception can be categorized as Built-in exceptions and User-defined exceptions.

Built-in Exceptions: These are defined by the programming languages you use.

User-defined exceptions: They are also called custom exceptions, where you can define your type of exception using the exception libraries.

Different Ways to Handle Exceptions in Selenium

Using the Throws to handle Exceptions in Selenium

The throws keyword can be used to specify the type of exception that is being thrown from a method.

The difference between the throw and throws keywords in Selenium Exception handling:

The throw keyword is used inside the block of code to throw a single exception. The throw keyword can be useful for throwing exceptions based on certain conditions within a code block and for throwing custom exceptions. The throws keyword is used in the method signature to declare an exception that might be thrown by the function during the execution of the code.

Example:

public static void someMethod() throws Exception {

//Your code that throw exception

}

Optionally, you can specify multiple exceptions in throws

Example:

public static void someMethod() throws Exception1, Exception2 {

//Your code that throw exception

}

Handling Selenium exceptions using the Try/Catch Block

The try/catch block mechanism is the most commonly used exception-handling mechanism. The try keyword is specified to a block where the exception will happen. In short, the try block contains the code that throws some exceptions. The try block must follow the catch block or finally block, or both. The catch block must be associated with the try block. This block is used to handle the exception that is thrown by the preceding try block.

Example

try{

driver.switchTo().alert().accept();

}

catch (NoAlertPresentException e){

//Write code to handle exception

}

Handling Selenium Exception using Multiple Catch Blocks

The Programming language allows us to have multiple catch blocks. This will help us when you expect more than one type of exception.

Example

try{

//Some code

}

catch (ExceptionType1 e){

//Write code to handle the exception

}

catch (ExceptionType2 e){

//Write code to handle the exception

}

Handling Selenium Exception using Nested Try-Catch blocks

A try-catch block can have another try-catch block within it. That is called a nested try-catch block.

Example

try{

//Some code

try{

// some code

}

catch (ExceptionType1 e){

//Write code to handle exception

}

}

catch (ExceptionType1 e){

//Write code to handle exception

}

catch (ExceptionType2 e){

//Write code to handle the exception

}

Exception handling with Finally block

The finally keyword is used to assign the block, which contains the code that needs to be executed irrespective of whether the exception is thrown. You can use a finally block along with the catch block. Typically, the Final block is used to free up the resources.

Example:

try{

//Some code

}

catch(Exception e){

}

finally{

//Code

}

Custom Exception in Selenium

Custom Exception provides flexibility to add attributes that are not part of the standard built-in exceptions. You can store custom information, which helps interpret the error messages quickly. However, an in-depth understanding of the programming language is required before creating the custom exception. A poorly designed custom exception may degrade the readability.

The Programming languages we use, such as Java, cover most of the common exceptions. However, you might need to define your own type of exception. Every programming language has its own way of defining a custom exception. Below is the Java example of defining a custom exception.

class InvalidAgeException extends Exception

{

public InvalidAgeException (String str)

{

super(str);

}

}

You can use the above exception using the following line of code

public static void someMethod()

{

try

{

throw new InvalidAgeException(“Invalid age”);

}

catch (InvalidAgeException ex)

{

System.out.println(” Exception Caught”);

}

}

Some of the important exception-handling functions available in Java:

  • getMessage(): The get method returns the details about the exception that occurred
  • getCause(): Returns the cause of the exception
  • printStackTrace(): Prints the stack trace
  • StackTraceElement [] getStackTrace(): Returns an array containing each element on the stack trace

New Exceptions in Selenium

Selenium keeps getting better with new versions. It also brings new exceptions to handle errors better. These exceptions help us to find and fix issues that were not clear before. Let’s check out some of the new exceptions:

ElementNotInteractableException

This exception happens when an element is in the DOM, but we can’t interact with it. It can be because the element is disabled, has an overlay, or is not fully loaded.

Example:

try {

    driver.findElement(By.id(“buttonId”)).click();

} catch (ElementNotInteractableException e) {

    System.out.println(“The button is not interactable: ” + e.getMessage());

}

InvalidCoordinatesException

This happens when mouse or touch actions fail due to wrong or out-of-bound coordinates. It is important when working with touchscreens and gestures.

Example:

try {

    Actions action = new Actions(driver);

    action.moveToElement(element, 1000, 1000).click().perform(); // Clicking outside the element

} catch (InvalidCoordinatesException e) {

    System.out.println(“Tried to interact with invalid coordinates: ” + e.getMessage());

}

InvalidSessionIdException

This exception occurs when a session ID is not valid or has expired. It can happen in long tests or if the session is interrupted.

Example:

try {

    WebDriver driver = new ChromeDriver();

    // … perform actions …

    driver.quit(); // Ends session

    driver.get(“someUrl”); // This will throw InvalidSessionIdException

} catch (InvalidSessionIdException e) {

    System.out.println(“Session is invalid or expired: ” + e.getMessage());

}

SessionNotCreatedException

This happens when WebDriver fails to start a new session. It can be due to an incompatible browser version or missing system files.

Example:

try {

    // ChromeDriver version may not match with installed Chrome

    WebDriver driver = new ChromeDriver();

} catch (SessionNotCreatedException e) {

    System.out.println(“Failed to create session: ” + e.getMessage());

}

ConnectionClosedException

This occurs when WebDriver loses connection. It can happen due to network problems or server issues.

Example:

try {

    WebDriver driver = new RemoteWebDriver(new URL(“http://localhost:4444/wd/hub”), capabilities);

    // … perform actions …

    // Network issues might cause this exception

} catch (ConnectionClosedException e) {

    System.out.println(“Connection to WebDriver was closed: ” + e.getMessage());

}

These new exceptions help us handle errors better in Selenium. By understanding them, we can write better test scripts that work well with modern web applications.

Exception Handling Best Practices

  • Handle common conditions without throwing exceptions
  • Design classes or methods so that exceptions can be avoided
  • Always predict the exception and have a try/catch/finally block inside your code
  • Write meaningful error messages
  • Create a custom exception as and when required to make it more readable
  • Catch the exception with the exact exception type; for example, rather than using Exception, use the concrete exception type ArithmeticException
  • Use the proper naming conventions when defining the custom exceptions
  • Differentiate between the test case errors (Assertion errors) and coding errors
  • Use the final block to clean up the resources

Summary

The exception handling mechanism has both advantages and disadvantages. The proper way of handling exceptions provides smooth functioning of your automation code. However, if it is used without understanding, the exception handling may mask the actual issues.

The exception handling and stack traces are also helpful in custom reporting, providing details about the exception along with the reason. However, building custom reporting libraries is complicated and takes more time. Moreover, custom reporting requires a deep understanding of the programming language and the test automation tool that is used. If you are a beginner or intermediate, then building such libraries is challenging. One of the easiest solutions is using a test automation tool like Testsigma.

Testsigma doesn’t require much coding knowledge as it is a codeless automation tool. Available as a SaaS product, you can just sign up and start using it. It has various incomparable features such as automatic test case generation, test report generation after each run, the ability to share the results without using any third-party tools, etc.

Frequently Asked Questions

What is the Webdriver Exception in Selenium?

The WebDriver Exception in Selenium is a common error. It happens when WebDriver faces an issue, mostly when it tries to do something after the WebDriver session is closed. This can occur if the WebDriver connection is lost or the browser is already shut. Handling this exception is important. It helps us find if the issue is from WebDriver talking to the browser or from the application we are testing. It acts like a catch-all for WebDriver problems. Instead of making the script fail, it gives useful feedback or logs the error for debugging.

What are the Different Selenium Exceptions?

Selenium has many exceptions to help find problems in test automation. One common exception is NoSuchElementException, which happens when the element is not found on the page. Another one is TimeOutException, which occurs when a command takes too long. ElementNotVisibleException appears when an element is present but can’t be seen. Then there is ElementNotInteractableException, which means an element is there but can’t be used. InvalidSessionIdException happens when there is a problem with the session. StaleElementReferenceException comes up when the element becomes invalid due to page reloads or DOM changes.

How to Handle Multiple Exceptions in Selenium?

To handle multiple exceptions in Selenium, we can use many catch blocks after a try block. Each catch block should catch a different type of error. This way, we can fix each issue in its own way. For example, we can have one catch for NoSuchElementException when an element is missing. Another catch for TimeOutException when something takes too long. This helps our script respond better to different errors and makes it stronger. We can also use nested try-catch blocks or one catch block with a general Exception type. This will catch any unknown error we should be careful because it can hide specific problems.

Selenium with Python
Selenium with Python: How to Run Automation Tests Using it?
Selenium Chromedriver
Selenium ChromeDriver & How to do Selenium Tests on Chrome?
Xpath in Selenium
Smart Ways to Use XPath in Selenium

Written By

G H

Testsigma Author - G H

G H

Seasoned Test Engineer, worked in multiple roles across the domains in the IT industry, passionate about writing blogs, technical articles, and helping the community in forum.

“Testsigma has been an absolute game-changer for us. We’ve saved time and caught critical issues that would’ve been missed with manual testing.“

- Bharathi K

Reach up to 70% test coverage with GenAI-based, low-code test automation tool.
User-friendly interface. Robust features. Always available support.

Testsigma - Momentum leader
Try for Free
imageimage
Subscribe to get all our latest blogs, updates delivered directly to your inbox.

By submitting the form, you would be accepting the Privacy Policy.

RELATED BLOGS