WebDriver Exceptions

Every programmer has to deal with exceptions or errors. Often beginner programmers get dishearten if their code start throwing Exceptions and they have no clue how to deal with it. In this tutorial, we’ll dig deeper to Exceptions world and will try to make friends with them.

If you want to be an efficient programmer you must read the error messages.

Some common WebDriver exceptions

  • NoSuchElementException
  • ElementNotVisibleException
  • StaleElementReferenceException
  • NoSuchWindowException
  • NoSuchFrameException
  • NoAlertPresentException


One of the most infamous exceptions NoSuchElementException. If you read the error stack trace it would be something like

org.openqa.selenium.NoSuchElementException: Unable to locate element

This exception occurs when we try to find the element using findElement() method and WebDriver determines there is no such element present with the specified locator. It could be due to the following reasons:

The element is not present in the page

This is the most obvious case that the target element is not present in the page. If this is the case you do not need to worry much. You can just report it as a bug.

There is one more possibility.

What if you are on the wrong page? Let’s say you clicked on the ‘Register’ link and expecting email field in the next page. It may happen that the click event failed, or the said link is dead so you were never on the Registration page. You need to keep this scenario in mind while writing code.

The locator is incorrect

Inspect the element and apply object identification techniques learned in the previous tutorials to fix the locator.

The element is taking time to load

Let’s say right after clicking Login button into Facebook you tried to validate Logout link but in practice, the homepage took time to load. In this case, the line of code that tries to find Logout will throw an exception – org.openqa.selenium.NoSuchElementException: Unable to locate element {“method”:”linkText”,”selector”:”Logout”}

To avoid it we need to apply to wait in our script before trying to find that element. You can read more about different kind of Waits available in WebDriver API in previous tutorials –

Leave a Reply