Know How To Handle Exceptions In Selenium

Neha Vaidya
Edureka
Published in
6 min readApr 25, 2019
Exceptions In Selenium — Edureka

With the world evolving towards software development, testing plays a vital role in making the process defect free. Automation testing using Selenium is one such tool that helps in finding bugs and resolve them. Exceptions in Selenium is an important concept which helps us in handling errors and avoid software failures. Through this article on Exceptions in Selenium, I will give you a complete insight into the fundamentals and various methods of handling exceptions.

In this article, I will be covering the following topics.

  • Introduction to Exception Handling
  • Checked vs Unchecked Exception
  • Basic Example of Exception
  • Types of Exceptions
  • Methods of Handling Exceptions

Introduction to Exceptions

An exception is an event or a problem that arises during the execution of a program. When an exception occurs, the normal flow of program halts and an exception object is created. The program then tries to find someone that can handle the raised exception. The exception object contains a lot of debugging information, such as method hierarchy, the line number where the exception occurred, the type of exception, etc.

When you start working with Selenium webdriver, you will come across different exceptions based on the code you write. The same code some times work properly and sometimes it simply doesn’t. Whenever you develop any script, you try to give the best quality code that works fine. But Unfortunately, sometimes exceptions come as side effects to the scripts that we develop and tends to fail. That’s why handling an exception is very important.

Exception Handling mechanism follows a flow which is depicted in the above figure. But if an exception is not handled, it may lead to a system failure. That is why handling an exception is very important. Now let’s move further and understand what are the various categories of exceptions.

Checked vs Unchecked Exception

Basically, there are 2 types of exceptions in Selenium and they are as follows:

  • Checked Exception
  • Unchecked Exception

Let’s understand these two exceptions in depth.

  • Checked Exception
    It is an exception that occurs at compile time, also called compile time exceptions. If some code within a method throws a checked exception, then the method must either handle the exception or it must specify the exception using throws keyword.
  • Unchecked Exception
    It is an exception that occurs at the time of execution and is called Runtime Exceptions. In C++, all exceptions are unchecked, but in Java, exceptions can be either checked or unchecked. So, it is not forced by the compiler to either handle or specify the exception. It is up to the programmers to specify or catch the exceptions.

Basic Example of Exception

class Exception{
public static void main(String args[]){
try{
//code that may raise an exception</span>
}
catch(Exception e){
// rest of the program
}
}
}

Above code represent an exception wherein inside try block we are going to write a code that may raise an exception and then, that exception will be handled in the catch block. Having understood this, let’s move further and see different types of exceptions that cause disruption to the normal flow of execution of the program.

Types of Exceptions

WebDriverException

WebDriver Exception comes when we try to perform any action on the non-existing driver.

WebDriver driver = new InternetExplorerDriver();
driver.get("http://google.com");
driver.close();
driver.quit();

NoAlertPresentException

When we try to perform an action i.e., either accept() or dismiss() which is not required at a required place; gives us this exception.

try{
driver.switchTo().alert().accept();
}
catch (NoAlertPresentException E){
E.printStackTrace();
}

NoSuchWindowException

When we try to switch to a window which is not present gives us this exception:

WebDriver driver = new InternetExplorerDriver();
driver.get("http://google.com");
driver.switchTo().window("Yup_Fail");
driver.close();

In the above snippet, line 3 throws us an exception, as we are trying to switch to a window that is not present.

NoSuchFrameException

Similar to Window exception, Frame exception mainly comes during switching between the frames.

WebDriver driver = new InternetExplorerDriver();
driver.get("http://google.com");
driver.switchTo().frame("F_fail");
driver.close();

In the above snippet, line 3 throws us an exception, as we are trying to switch to a frame that is not present.

NoSuchElementException

This exception is thrown when we WebDriver doesn’t find the web-element in the DOM.

WebDriver driver = new InternetExplorerDriver();
driver.get("http://google.com");
driver.findElement(By.name("fake")).click();

Now see move ahead in this exceptions in Selenium article and see various methods used to handle Exceptions.

Methods of Handling Exceptions

  1. Try: try block is used to enclose the code that might throw an exception.
  2. Catch: catch block is used to handle the Exception. It must be used after the try block only
  3. Finally: finally block is a block that is used to execute important code such as closing connection, stream etc. It is always executed whether an exception is handled or not.
  4. Throw: throw” keyword is used to throw an exception.
  5. Throws: The “throws” keyword is used to declare exceptions. It doesn’t throw an exception. It specifies that there may occur an exception in the method. It is always used with method signature.

Let’s see a small example to understand how a thrown exception can be handled using exception methods. Let’s have a look at the code.

package Edureka;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.openqa.selenium.By;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Exceptionhandling {
public static void main(String[] args) throws InterruptedException, TimeoutException{
System.setProperty("webdriver.firefox.driver", "C:\\Selenium-java-edureka\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new FirefoxDriver();
WebDriverWait wait = new WebDriverWait(driver, 10);
driver.get("https://www.google.com");
try{
driver.findElement(By.xpath("//*[@id='register']")).click();
}catch (Exception e) {
System.out.println("Register element is not found.");
throw(e);
}
System.out.println("Hello");
}
}

Let’s understand the functionalities of each method in depth.

Try Method

In the above code, I have used a try block to enter the statement that throws the exception. Here, this statement driver.findElement(By.xpath(“//*[@id=’register’]”)).click(); throws exception because in the Google Search page Selenium cannot locate the particular element. So, once the exception is thrown, the normal execution of the program will be interrupted. Now, let’s see how it is handled in the catch block.

Catch Method

The task here is to handle this exception and continue the execution of the program. For that, I have written a catch block which will handle the thrown exception. It should always be written after the try block. So when you execute the program, it will print the rest of the statements.

Throw Method

As you all know throw is a keyword which is used to pass an exception. But, the interesting thing is that irrespective of the fact that catch block has handled the exception or not,will still raise an exception. This results in disrupting the normal flow of execution of the program. In the above code, after the catch block has handled the exception, I have written a statement to throw an exception.

Throws Method

Throws declaration is used to declare an exception. For example, It can declare Interrupted exception, timeout exception, etc. This is how various methods can be used to handle the raised exception in the program.

With this, we come to an end of this article on Exceptions in Selenium. I hope you understood the concepts and helped in adding value to your knowledge.

If you wish to check out more articles on the market’s most trending technologies like Artificial Intelligence, DevOps, Ethical Hacking, then you can refer to Edureka’s official site.

Do look out for other articles in this series which will explain the various other aspects of Selenium.

1. Selenium Tutorial

2. Selenium WebDriver: TestNG For Test Case Management & Report Generation

3. Building A Data Driven, Keyword Driven & Hybrid Selenium Framework

4. Locators in Selenium

5. XPath Tutorial

6. Waits in Selenium

7. Setting up a Selenium Grid for distributed Selenium testing

8. Selenium Using Python

9. Cross Browser Testing Using LambdaTest

10. Cross Browser Testing Using Selenium

11. Handle Multiple Windows in Selenium

12. Page Object Model In Selenium

13. Selenium Projects

14. QTP vs Selenium

15. Selenium vs RPA

16. Selenium WebDriver Architecture

17. Perform Website Testing Using Cucumber & Selenium

Originally published at https://www.edureka.co on April 25, 2019.

--

--