We know that an exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program’s instructions. When an error occurs within a method, the method creates an object and hands it off to the runtime system. This block of code is called an exception handler.
In real world scenario, while working with automation using Selenium WebDriver, automation engineer would definitely come across various exceptions which disrupts the test case execution. The automation script that you work with, sometimes work properly and sometimes it simply doesn’t work. For any script that you develop, make sure that you deliver the best quality code with proper exceptions handling techniques implemented.
In this article, I would like to share the common exceptions while selenium automation execution and also the solutions to handle those exceptions. Following are the different types of exceptions in selenium,
WebDriverException
WebDriverException arises when the your code tries to perform any action on the non-existing browser. For example, trying to use driver after closing the driver session.
WebDriver driver = new ChromeDriver();
driver.get(“https://journeyofquality.com/ “);
driver.close();
driver.findElement(By.id(“bu345”)).click();
Solution: You can handle this WebDriverException by using driver.close() after the completion of all tests at @AfterSuite annotation if you are using TestNG instead of using them after each test case that is after all the test execution has completed.
SessionNotFoundException
SessionNotFoundException will occur when driver is trying to perform operations on the web application after the browser is quitted by driver.quit().
@Test
public void openJourneyOfQuality() {
driver.get(“https://journeyofquality.com/ “);
Assert.assertEquals(“Journey”, driver.getTitle());
driver.quit();
Assert.assertEquals(“https://journeyofquality.com/ “, driver.getCurrentUrl());
}
Solution: This exception can be handled by using driver.quit() after the completion of all tests instead of using them after each test case. This can lead to issues when driver instance becoming null and following test cases try to use it without initializing. We can kill the driver instance after all the test execution has completed and hence we can add them up at @AfterSuite of TestNG annotation.
StaleElementReferenceException
User would come across StaleElemenReferenceException mainly when Selenium navigates to a different page, come backs to the same old page and performs operations on the old page which is no longer available. Technically, it occurs when the element defined in the script is not found in the cache memory and script is trying to locate it that particular element. When we inspect and locate an element on a page using Selenium, it is stored in a cache memory which gets deleted when the driver navigates to another page during execution. When user navigates back to old page and then while trying to access the cache removed element on the old page, we will get StaleElementReferenceException during the automation script execution.
Solutions:
- Refresh the webpage and perform action on that web element.
- Include the web element on try-catch block within for loop to get the element and perform the action. Once it perform the action, it will break from the loop.
for (int value = 0; value <= 2; value++) {
try {
driver.findElement(By.xpath(“webElement”)).click();
break;
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
- Wait for the element till available by using ExpectedConditions,
wait.until(ExpectedConditions.presenceOfElementLocated(By.id(“webElement”)));
NoSuchElementException
NoSuchElementException occurs, when the element locators we provided in the Selenium script is unable to find that web element on the web page. Probably this will happen in two ways,
- When we have provided an incorrect locator and trying to find the web element.
- We have provided correct locator, but the web element related to the locator is not available on the web page. That means the action performed before loading that element on the web page.
@Test
public void testJourney() {
driver.get(“https://journeyofquality.com/ “);
try {
driver.findElement(By.id(“invalidelement”)).click();
} catch (NoSuchElementException e) {
System.out.println(“No Such Element exceptional case”);
}
}
In the above code, trying to locate an element with id invalidelement on website page. When the element is not found, the application throws NoSuchElementException.
Solution: Make sure that the locator (XPath/Id) provided is correct or try to use the explicit wait methods for the presence of element and then perform the action on it. For example,
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.presenceOfElementLocated(By.id(“invalidelement”)));
ElementNotVisibleException
ElementNotVisibleException is thrown when WebDriver tries to perform an action on an invisible web element, which cannot be interacted with since element is in a hidden state. For example, there is no button displayed on the web page and if there is HTML code related to the button, then on trying to click on that particular button using locators in the automation script and we will get ElementNotVisibleException. These exception can happen even if the page has not loaded completely and when user tries to interact with an element.
Solution: We have to wait until that particular element becomes visible on web page. To tackle this you can use the explicit wait methods in Selenium. For example,
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(“invisibleElement”));
NoSuchFrameException
On the webpage, user may have to deal with HTML documents that are embedded inside another HTML document which are called as iframe. In order to work with the web elements on any iframe, we have to first switch to that particular iframe in Selenium by using frame-name or frame-ID and then inspect and locate the respective web elements inside the iframe. NoSuchFrameException occurs, when the driver in the Selenium script is unable to find the frame on the web page to switch which happens when the driver is switching to an invalid or non-existing iframe.
Solution: We have to wait until that particular frame to be available on web page. To tackle this, you can use the explicit wait methods in Selenium. For example,
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.frameToBeAvaliableAndSwitchToIt(frame_id));
NoAlertPresentException
Alert is a pop-up which provide important information to users or asking for perform certain operation like reading the messages on the alerts or accepting the alert by pressing OK button on the alert or dismissing the alert by pressing CANCEL button etc. In order to work with Alert pop-ups, we have to first switch to Alert and then perform operations on Alert window. NoAlertPresentException occurs when the driver in the script is unable to find the Alert on the web page to switch when the driver is switching to an invalid or non-existing Alert pop-up. Sometime NoAlertPresentException exception is thrown even if the alert is not loaded completely.
Solution: To handle NoAlertPresentException include the script inside try-catch block and provide explicit wait for the alert to be available as shown below.
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.alertIsPresent());
NoSuchWindowException
We know that Selenium automates Web applications only, and in real time we may have to deal with browser windows which will be opened when you click on buttons or links. In order to interact with the Web Elements on any browser pop-up window, we have to handle all the opened windows and then locate the respective web elements inside the pop-up window. NoSuchWindowException occurs when the driver in the script is unable to find the pop-up window on the web page to switch. NoSuchWindowException is thrown if the window handle doesn’t exist or is not available to switch.
Solution: We would iterate through all the active windows handles and perform the desired actions. For example,
for(String handle: driver.getWindowHandles()) {
try {
driver.switchTo().window(handle);
} catch (NoSuchWindowException e) {
System.out.println(“No such window exceptional case”);
}
}
TimeoutException
Waits are mainly used in WebDriver to avoid the exception like ElementNotVisibleException which occurs while trying to click on a button before the page is completely loaded. This exception occurs when a command takes more than the wait time completion. However, if the components doesn’t load even after the wait time mentioned, the exception org.openqa.selenium.Timeoutexception will be thrown.
Solution: To avoid this exception, waits commands are added either implicit, explicit or fluent wait.
Implicit Wait:
The Implicit Wait in Selenium is used to tell the web driver to wait for a certain amount of time before it throws a NoSuchElementException. The default setting is 0. Once we set the time, the web driver will wait for the element for that time before throwing an exception. For example,
driver.manage().timeouts().implicitlyWait(15,TimeUnit.SECONDS) ;
driver.get(“https://journeyofquality.com/ “);
In the above code, an implicit wait of 15 seconds is added. If the page https://journeyofquality.com/ doesn’t load in 15 seconds, then TimeoutException will be thrown.
Explicit Wait:
The Explicit Wait in Selenium is used to tell the Web Driver to wait for certain conditions (Expected Conditions) or maximum time exceeded before throwing ElementNotVisibleException exception. It is an intelligent kind of wait, but it can be applied only for specified elements. We already discussed few examples above related to explicit wait like,
wait.until(ExpectedConditions.presenceOfElementLocated(By.id(“webElement”)));
wait.until(ExpectedConditions.frameToBeAvaliableAndSwitchToIt(frame_id));
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(“invisibleElement”));
Fluent Wait:
The Fluent Wait in Selenium is used to define maximum time for the web driver to wait for a condition, as well as the frequency with which we want to check the condition before throwing an ElementNotVisibleException exception. It checks for the web element at regular intervals until the object is found or timeout happens. Frequency is setting up a repeat cycle with the time frame to verify or check the condition at the regular interval of time. Below is the sample implmentaion for fluent wait,
Wait wait = new FluentWait(WebDriver driver)
.withTimeout(Duration.ofSeconds(SECONDS))
.pollingEvery(Duration.ofSeconds(SECONDS))
.ignoring(Exception.class);
Overall Exception Handling Solutions
In order to handle these above types of Selenium exceptions, we will use following exception handling mechanism,
Throw: Throw keyword is used to throw exception to the runtime to handle it.
public static void anyMethod() throws Exception{
try{
// write your code here
}catch (Exception e){
// Do whatever you wish to do here
// Now throw the exception back to the system
throw(e);
}
}
Multiple Catch Blocks: You can use multiple catch() blocks to catch different types of exception. The syntax for multiple catch blocks looks like the following:
public static void anyMethod() throws Exception{
try{
// write your code here
}catch(ExceptionType1 e1){
//Code for Handling the Exception 1
}catch(ExceptionType2 e2){
//Code for Handling the Exception 2
}
Try/Catch: A try block encloses code that can potentially throw an exception. A catch() block contains exception-handling logic for exceptions thrown in a try block. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following:
public static void anyMethod() throws Exception{
try{
// write your code here
}catch(Exception e){
//Code for Handling the Exception
}
}
Finally: A finally block contains code that must be executed whether an exception is thrown or not:
public static void anyMethod() throws Exception{
try{
// write your code here
}catch(ExceptionType1 e1){
//Code for Handling the Exception 1
}catch(ExceptionType2 e2){
//Code for Handling the Exception 2
}
finally{
//The finally block always executes.
}
}
I hope you got an idea on various common selenium exceptions, the solutions and the general way to handle those exceptions. Try to implement these exception handling mechanism in your automation script and handle these runtime anomalies.
make it perfect!
Leave a Reply