DEV Community

Saravanan Devaraj
Saravanan Devaraj

Posted on

Exceptions in Selenium: Complete Tutorial

As automation specialists, we would have encountered errors and exceptions in our code. While both the terms indicate an issue, there is a clear-cut difference between them.

Let’s understand exceptions and errors with a real-life scenario first. Imagine that you’re at the ATM to withdraw cash. You enter the wrong PIN and the system throws an error message asking you to enter the correct PIN and if the limit is exceeded, the card is blocked. This is a serious situation and this is what an error looks like.

Now let's imagine that you went to the ATM as a kid and wanted to try out the machine. You get the card and insert it in the reverse direction. The ATM is unable to read the card and prompts you to insert the card correctly. You try out the other way and voila! your card is now read by the machine. Now, this is a less severe issue that was easily rectified. This can be compared to an exception. Let's dive into the technical terms now.

An event that occurs during a program’s execution and disrupts its instruction flow is an exception. While an error occurs before runtime due to factors compromised in the system resources, exceptions are issues that occur during runtime/compile time.

In Selenium, we may get exceptions due to incorrect parameters, time-outs, syntaxes, network stability issues, browser compatibility issues, etc. Handling exceptions in Selenium is a skill that any automation coder should possess and it is a major segment of Selenium interview questions. Before diving into the types of exceptions in selenium, let’s understand the type of exceptions in JAVA.

Here are the types of exceptions:

  • Checked exception: This type of exception is handled during compile time. If it is not caught it gives a compilation error during compile time. FileNotFoundException, IOException, etc are a few examples
  • Unchecked exception: The compiler ignores this exception during compile time. However, this may create an issue in the outputs. ArrayIndexoutOfBoundException is one fine example

So how do we handle these exceptions? With the following methods of course!

Try and catch block

This is the most common way to handle exceptions that are expected to be declared in the catch block. When an exception occurs in the try block, the control is shifted to the catch block. Depending upon the type of exception there can be n number of catch blocks for one try block.

try{
Br = new BufferedReader(new FileReader("example"));
}
catch(IOException ie){
ie.printStackTrace();
}
catch(FileNotFoundException file){
file.printStackTrace();
}
Enter fullscreen mode Exit fullscreen mode

Throws exception

This method can be used on all checked exceptions. The throws keyword is used to throw an exception rather than handle it.

Public static void main(String[] args) throws IOException{
BufferedReader br=new BufferedReader(new FileReader("Example"));
while ((line = br.readLine()) != null)
{
System.out.println(line);
}
Enter fullscreen mode Exit fullscreen mode

Finally block

The finally block is executed immediately after the completion of the try and catch block. It does not depend on the try and catch block and can exist even in the absence of a catch block. Steps like file closing, database connections, etc can be closed using finally block.

try{
Br = new BufferedReader(new FileReader("Example"));
}
catch(IOException ie)
{
ie.printStackTrace();
Finally
{
br.close();
}
Enter fullscreen mode Exit fullscreen mode

Throwable

What happens in cases where the programmer is not sure about the type of exception? They can use the parent class called throwable for errors and exceptions!

try {
Br = new BufferedReader(new FileReader("Example"));
}
Catch (Throwable t)
{
t.printStackTrace();
}
Enter fullscreen mode Exit fullscreen mode

Now that we have an idea about exceptions and exception handling in general, let's get to the exceptions in selenium. With this, you can handle exceptions as well as Selenium Interview questions concerning the same!

Handling exceptions in Selenium

The runtime exception classes in Selenium WebDriver belong to the superclass WebDriverException. While there are an umpteen number of exceptions available, here are the most common exceptions in Selenium that we encounter:

  • NoSuchElementException
  • NoSuchWindowException
  • No-SuchFrameException
  • NoAlertPresentException
  • InvalidSelectorException
  • ElementNotVisibleException
  • ElementNotSelectableException
  • TimeoutException
  • NoSuchSessionException
  • StaleElementReferenceException

NoSuchElementException

This exception occurs when the Selenium WebDriver is unable to find/locate the elements specified in the script. This is a pretty simple exception and can be rectified by cross-checking the element locator given in the findElement(By, by) method. In the case of using the Page class in the scripts, make sure that the element locators are updated in the Page Object Model class, in case there’s a change in the UAT’s code.
For example, if the ID for the login button was “login” first and now changed to “loginsuccess”, the WebDriver obviously cannot locate the element and the org.openqa.selenium.NoSuchElementException is thrown. Sometimes even this exception is thrown even when the element is not downloaded. We can include an implicit wait or a thread.sleep code to give the UAT time for its contents to be downloaded fully.

driver.findElement(By.id("login")).click();`
Enter fullscreen mode Exit fullscreen mode

Exception handling using try and catch block:

try{
driver.findElement(By.id("login")).click();
} catch (NoSuchElementException e)
Implicit wait and thread.sleep in Selenium:
Package waitExample;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class WaitTest {

public WebDriver driver;
public String Url;
public WebElement element;

@BeforeMethod
public void setUp() throws Exception {
driver = new FirefoxDriver();
Url = ("https://www.example.com");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}`

@Test
public void testun() throws Exception {
driver.get(Url);
element = driver.findElement(By.id("abc"));
Thread.sleep(1000)
element.sendKeys("testdata");
element.sendKeys(Keys.RETURN);
List<WebElement> 
list = driver.findElements(By.className("test"));
System.out.println(list.size());

}

@AfterMethod
public void tearDown() throws Exception {
driver.quit();
}
}
Enter fullscreen mode Exit fullscreen mode

Usage of implicit waits, thread.sleep etc come under the avoid-handling approach in exceptions in Selenium.

NoSuchWindowException

This exception is thrown when the WebDriver tries to switch to a supposedly invalid window. We can prevent this exception from occurring by introducing a driver switch for each window at each stage of code execution.

for (String handle : driver.getWindowHandles()) {
try {
driver.switchTo().window(handle);
} catch (NoSuchWindowException e) {
driver.quit();
}
}
Enter fullscreen mode Exit fullscreen mode

The avoid-handling technique for this issue would be to include a wait time in the automation scripts. Since this comes under the NotFoundException class, we can use the previous troubleshooting methods also.

NoSuchFrameException

When a frame is invalid or does not exist, the no such frame exception in Selenium is thrown. This exception belongs to the NotFoundException class.

try {
driver.switchTo().frame("frame_2");
} catch (NoSuchWindowException e)
Enter fullscreen mode Exit fullscreen mode

We all know that all the components in a website may take time to be downloaded fully. So there are chances that the frame hasn’t been downloaded yet. Here we can use an explicit wait command to check if the frame appears within a timespan and if not, the exception is thrown.

try {
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(frame_10));
try {
driver.switchTo().frame("frame_10");
} catch (WebDriverException e) {
System.out.println("abcd");
}
} catch (TimeOutException e) {
System.out.println("frame not located");`
}
Enter fullscreen mode Exit fullscreen mode

NoAlertPresentException

Just like the above exceptions, this also belongs to the NotFoundException class. This exception is thrown when the Selenium WebDriver tries to switch to an alert that is not yet available on the screen or does not exist. In this case, we can use an explicit or a fluent wait command to wait till the alert is loaded fully, and if not, then the exception can be thrown.

try {
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until(ExpectedConditions.alertIsPresent());
try {
driver.switchTo().alert().accept();
} catch (TimeOutException e)
System.out.println("Alert not found");`
}
Enter fullscreen mode Exit fullscreen mode

InvalidSelectorException

XPATH locator method may seem to be accurate, but if there is a syntax issue in our custom XPATH, we are bound to get an invalid selector exception. This may happen with other locators also. The Invalid Selector exception in Selenium occurs when the selector is invalid or when the syntax is incorrect.

try {
clickXPathButtonAndWait("//button[@type='button1']");
} catch (InvalidSelectorException e) {
}
Enter fullscreen mode Exit fullscreen mode

ElementNotVisibleException

When the WebDriver tries to interact with any invisible or hidden element, the ElementNotVisibleException is encountered. This exception also belongs to the ElementNotVisibleException class. Sometimes, when the page is not downloaded completely, chances are that the ElementNotVisibleException is thrown. Just like the previous exceptions, here also we can use explicit wait to check if the element appears within a stipulated time, or else the exception is thrown.

try {
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(15));
wait.Until(ExpectedConditions.visibilityOfElementLocated(By.id("test"));
try {
driver.findElement(By.id("test")).click();
} catch (TimeOutException e)
System.out.println("Element not visible");
}
Enter fullscreen mode Exit fullscreen mode

ElementNotSelectableException

When the web element is present on the web page but is not enabled, then the ElementNotSelectableException occurs. This happens with dropdown menus, radio buttons, toggles, etc. The superclass of this exception is the InvalidElementStateException. As an avoiding-and-handling technique, we can add an explicit wait command to wait till the element is enabled and interactable.

try {
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(15));
wait.Until(ExpectedConditions. elementToBeClickable(By.id("test"));
try {
Select dropdown = new Select(driver.findElement(By.id("test")));
} catch (ElementNotSelectableException e)
System.out.println("Element not enabled");
}
Enter fullscreen mode Exit fullscreen mode

TimeoutException

In the above exceptions, we have used wait commands as a workaround. But what happens if a command’s execution time exceeds the wait time? What happens when the elements aren’t loaded completely even after the wait time? Now this seems to be a challenging part of the Selenium Interview questions!
The TimeoutException is thrown in this case. We can manually observe the time taken by the webpage to download its components completely and alter our scripts, or else we can add an explicit wait using a JavaScript executor. Here’s an example:
Let’s consider a mock website called “www.exampletestselenium.com”. After page navigation, we can use the return type document.readyState for 30 seconds until the value “complete” is returned. Since JavaScript is the browser’s native language, we tend to encounter fewer issues while using the JavaScript executor correctly.

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));

wait.until(webDriver -> ((JavascriptExecutor)webDriver).executeScript("return document.readyState").equals("complete"));

driver.get("https://www.exampletestselenium.com");`
Enter fullscreen mode Exit fullscreen mode

NoSuchSessionException

This exception occurs when the WebDriver is not able to execute any command using the driver instance. Issues like browser crashes are a solid reason for this exception to occur. To prevent this exception, we must ensure that the browser version that we use is stable and the drivers must be compatible with the browser versions. Using the driver.quit() method at the end of all tests can help minimize the occurrence of this exception to a great extent.

@BeforeSuite
public void setUp() throws MalformedURLException {
WebDriver driver = new ChromeDriver();
}
@AfterSuite
public void testDown() {
driver.quit();
}
Enter fullscreen mode Exit fullscreen mode

StaleElementReferenceException

We often encounter this exception when there is navigation to a new page, the DOM has been refreshed, or during a window /frame switch. In this case, the element is no longer present on the web page, and when the WebDriver tries to find it, the exception occurs. However, this is not the same as ElementNotVisibleException. In ElementNotVisibleException, the elements are hidden or loaded late, whereas, in StaleElementReferenceException, the elements are not present on the current web page. For example, the user may want to enter his username in the username field. But a window switch was done while clicking on the login button from the home page. When the object is created first and the switch is commanded later, an exception occurs
To avoid this exception, we can try using a dynamic XPath.

try {
driver.findElement(By.xpath("//*[contains(@id,username')]")).sendKeys("testid");
} catch (StaleElementReferenceException e)
Enter fullscreen mode Exit fullscreen mode

Conclusion

I hope this article gave you a clear understanding of exceptions in Selenium. Keep learning and practicing until those Selenium Interview questions become a cakewalk for you!

Latest comments (0)