Table of contents
1.
Introduction
2.
What are Exceptions?
3.
List of Exceptions in Selenium
3.1.
Timeout Exception
3.2.
NoSuchWindow Exception
3.3.
UnreachableBrowser Exception
3.4.
NoSuchSession Exception
3.5.
NoSuchElement Exception
3.6.
ElementNotVisible Exception
3.7.
StaleElementReference Exception
4.
Handling Exceptions
5.
Types of Exceptions in Java and Selenium
6.
Advantages of the Avoid-Handle Approach
7.
Disadvantages of the Avoid-Handle Approach
8.
Frequently Asked Questions
8.1.
What are checked exceptions in Selenium?
8.2.
What is the ‘finally’ keyword?
8.3.
What are the different browsers and languages supported by the Selenium web driver?
9.
Conclusion
Last Updated: Mar 27, 2024
Easy

Exceptions in Selenium

Author Abhinav Anand
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In Selenium, exceptions occur when errors are improperly handled in your test code. They usually interrupt the normal execution of your test.

exceptions in selenium

In this article, you will learn about Selenium exceptions and measures you can take to handle them. 

What are Exceptions?

In Selenium, exceptions are errors that occur during the execution of your testing code. These exceptions can be caused by a variety of reasons, such as an element not being found, a timeout, or an invalid input. They interrupt the regular execution of your program and must be handled using features such as try-catch blocks.

The next section will introduce you to the different types of exceptions in Selenium.

List of Exceptions in Selenium

The following are some exceptions that commonly occur when you use the Selenium web driver:-

Timeout Exception

This exception occurs when an operation takes more time to complete than specified. It happens when you wait for an element to be visible or interactable.

The web driver throws the time exception after waiting longer than the specified time.

terminal output

NoSuchWindow Exception

This exception occurs when the web driver cannot find the pop-up window it launched initially. You can recreate it by simply closing the window launched by the web driver.

The driver throws this exception in the given output after the testing window is closed manually.

terminal output

UnreachableBrowser Exception

This exception occurs when the driver cannot open the browser window for some reason, such as incompatibility or crashes.

NoSuchSession Exception

This exception occurs when you try to execute commands after driver.quit() has been performed.

The following code will result in this exception.

const {Builder, Browser, By, Key, until} = require('selenium-webdriver');


(async function example() {
  let driver = await new Builder().forBrowser(Browser.CHROME).build();
    await driver.get('https://www.google.com/');
    await driver.findElement(By.name('q')).sendKeys('Coding Ninjas', Key.RETURN);
    await driver.quit() //browser window will be closed
    const actions = driver.actions()
    await actions.sendKeys('Coding Ninjas', Key.RETURN).perform()    
})();

 

Result 

The terminal output for the code above is shown below.

terminal output

NoSuchElement Exception

This exception occurs when a specified element cannot be found. It usually happens when you use an incorrect id or class name.

ElementNotVisible Exception

If an element is hidden using HTML hidden attribute or CSS, it cannot be selected by the driver. This results in the ElementNotVisible exception.

StaleElementReference Exception

This exception occurs when a previously selected element is accessed after it is no longer a part of the HTML DOM.

The following script selects an element on the first page, then tries to access it after browsing to a different page. This results in the StaleElementReference exception:-

const { Builder, Browser, By } = require('selenium-webdriver');


(async function example() {
  let driver = await new Builder().forBrowser(Browser.CHROME).build();
  await driver.get('https://www.codingninjas.com/')
  let clickable = await driver.findElement(By.id("web-enrol-now"))//selected element
  const actions = driver.actions()
  await driver.get('https://www.codingninjas.com/studio')
  await actions.move({origin: clickable}).click().perform()//element is not stale
})();

 

Result 

The web driver throws the StaleElementReference exception when we try to execute the move and click action on an element from the previous page.

terminal output

Handling Exceptions

Exceptions stop the regular flow of your testing code or script, which may result in unexpected side effects. Like other frameworks, Selenium also supports try-catch blocks, which helps you protect vulnerable parts of your code by catching exceptions before they break the flow of your code.

The following code uses an invalid id to select an element, leading to a NoSuchElement exception. Since the try-catch block intercepts the exception, the remaining code executes successfully even after the exception occurs.

const { Builder, Browser, By } = require('selenium-webdriver');


(async function example() {
  let driver = await new Builder().forBrowser(Browser.CHROME).build();


  await driver.get('https://www.codingninjas.com')


  try {
    const clickable = await driver.findElement(By.id("invalid-id"))
  } catch (error) {
    console.log('Error')
  }


  const el = await driver.findElement(By.xpath(`/html/body/landing-root/landing-landing-app-v2/div/div/landing-landing-page-v2/shared-ui-footer-v2/div[1]`))
  await driver.actions()
    .scroll(0, 0, 0, 0, el)
    .perform()
})();

 

Terminal Output Displaying Exception

terminal output

Driver Executing Scroll Command

driver testing window

As you can see, the driver executes the scroll action even after the exception occurs.

There are multiple ways to handle exceptions. However, we have only discussed the most straightforward way out of them.

Types of Exceptions in Java and Selenium

In Java and Selenium, exceptions are used to handle unexpected situations or errors that may occur during the execution of a program or a test script. Here are some common types of exceptions in Java and Selenium:

Java Exceptions

1. ArithmeticException: Thrown when an arithmetic operation (such as division by zero) results in an undefined mathematical result.

int result = 10 / 0; // ArithmeticException

 

2. NullPointerException: Occurs when attempting to access an object or invoke a method on an object that is null.

String str = null;
int length = str.length(); // NullPointerException

 

3. ArrayIndexOutOfBoundsException: Thrown when trying to access an array element with an index outside the valid range.

int[] numbers = {1, 2, 3};
int value = numbers[5]; // ArrayIndexOutOfBoundsException

 

4. FileNotFoundException: Raised when attempting to access a file that does not exist.

FileInputStream file = new FileInputStream("nonexistent.txt"); // FileNotFoundException

 

5. IOException: A general exception for I/O-related errors, including file operations, network operations, etc.

FileReader fileReader = new FileReader("file.txt");
char[] buffer = new char[1024];
fileReader.read(buffer); // IOException

 

Selenium Exceptions

1. NoSuchElementException: Thrown when attempting to locate an element using methods like findElement() or findElements(), but the element is not found on the web page.

WebElement element = driver.findElement(By.id("nonexistentId")); // NoSuchElementException

 

2. TimeoutException: Occurs when a command or operation times out due to the specified timeout period being exceeded.

WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("elementId"))); // TimeoutException

 

3. ElementNotVisibleException: Raised when attempting to interact with an element that is present in the DOM but not visible on the web page.

WebElement element = driver.findElement(By.id("hiddenElementId"));
element.click(); // ElementNotVisibleException

 

4. StaleElementReferenceException: Thrown when the element reference becomes "stale" or no longer valid because the web page has been refreshed or changed.

WebElement element = driver.findElement(By.id("elementId"));
driver.navigate().refresh();
element.click(); // StaleElementReferenceException

 

5. WebDriverException: A general exception for WebDriver-related errors, covering various issues that may occur during test execution.

driver.get("https://example.com");
driver.quit(); // WebDriverException (if an issue occurs during browser closure)

Advantages of the Avoid-Handle Approach

The advantages of the avoid-handle approach are:

  • Early Detection of Issues: By avoiding exceptions rather than handling them, developers are encouraged to write code that prevents issues from occurring in the first place. This promotes early detection and resolution of potential problems.
  • Improved Code Readability: Code written with the avoid-handle approach tends to be more straightforward and readable. Developers can focus on the main logic of the program rather than cluttering it with numerous exception-handling blocks.
  • Enhanced Code Maintainability: Code that follows the avoid-handle approach often requires fewer modifications when making changes to the codebase. This can result in improved maintainability and a reduced likelihood of introducing new issues.
  • Prevention of Unintended Side Effects: Exception handling can introduce unintended side effects or create complexity in the code flow. Avoiding exceptions reduces the risk of introducing unexpected behavior and makes it easier to reason about the code.
  • Promotion of Defensive Programming: Developers are encouraged to adopt a defensive programming mindset, anticipating potential issues and designing code to prevent them. This proactive approach can lead to more robust and reliable software.

Disadvantages of the Avoid-Handle Approach

The disadvantages of the avoid-handle approach are:

  • Limited Error Recovery: In situations where errors are inevitable (e.g., dealing with external systems or user input), the avoid-handle approach may limit the ability to recover gracefully from errors. This can result in less resilient systems.
  • Increased Complexity in Preventive Measures: Writing code to avoid exceptions might require additional checks, validations, or defensive measures, potentially increasing the complexity of the code. Striking the right balance between prevention and simplicity can be challenging.
  • Overhead in Performance: Preventive measures to avoid exceptions may introduce additional overhead, affecting the performance of the application. This is particularly relevant in performance-sensitive applications where every resource is critical.
  • Potential for Code Duplication: Avoiding exceptions might lead to duplicating code for error checks and validations across multiple parts of the program. This can make maintenance more challenging, as any changes must be applied consistently.
  • Trade-off Between Safety and Development Time: Emphasizing the avoid-handle approach may lead to a trade-off between safety and development time. Writing extensive preventive measures can be time-consuming, and there might be situations where a more balanced approach with proper exception handling is preferable.
  • Limited Support for Asynchronous Operations: In scenarios involving asynchronous or parallel operations, avoiding exceptions might be more challenging, as errors may occur in a different context or thread. Proper handling becomes crucial in such cases.

Check this out : Xpath in Selenium

Frequently Asked Questions

What are checked exceptions in Selenium?

Checked exceptions occur during the compilation of your testing code. It is not a term used for Selenium web driver exceptions, and it is instead used for Java exceptions.

What is the ‘finally’ keyword?

This keyword is used with try-catch blocks to mark code that will always run even if an exception occurs. In selenium scripts, it is commonly used for executing driver.close() command.

What are the different browsers and languages supported by the Selenium web driver?

It supports several browsers (Google Chrome 12+, Internet Explorer 7,8,9,10, Safari 5.1+, Opera 11.5, Firefox 3+). For the Selenium web driver, you can write testing code or scripts with different programming languages such as C#, Java, JavaScript, Ruby, and Python.

Conclusion

In Selenium, exceptions are errors that occur during the execution of a test script. A variety of reasons can cause these exceptions. Handling exceptions is essential to writing robust and reliable test scripts in Selenium.

Hope this article helped you understand the different types of exceptions in Selenium and exception handling.

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enroll in our courses and refer to the mock test and problems available. Take a look at the interview experiences and interview bundle for placement preparations.

Happy Learning!

Live masterclass