Exceptions in Selenium – Know How To Handle Exceptions

Last updated on Sep 11,2024 29.2K Views
A tech enthusiast in Java, Image Processing, Cloud Computing, Hadoop. A tech enthusiast in Java, Image Processing, Cloud Computing, Hadoop.

Exceptions in Selenium – Know How To Handle Exceptions

edureka.co

With the world evolving towards software development, testing plays a vital role in making the process defect free. Selenium is one such tool that helps in finding bugs and resolve them. The Selenium Certification can help you learn all about exceptions. Exceptions in Selenium is an important concept that 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.

You may also go through this recording of Exceptions in Selenium by our Experts where you can understand the topics in a detailed manner with examples.

Handle Exceptions in Selenium Webdriver | Popular Selenium Exceptions | Edureka


This video will talk about exception handling in selenium. It will also tell you about various types of exceptions and how to handle them using various methods.

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:

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

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();

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();
}

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.

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.

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.

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.

Find out our Selenium Training in Top Cities/Countries

IndiaOther Cities/Countries
BangaloreUS
HyderabadUK
PuneCanada
ChennaiAustralia
MumbaiSingapore
KolkataEdinburgh

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-edurekachromedriver_win32chromedriver.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, throw()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 throw(e); 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.

Got a question for us? Please mention it in the comments section of Exceptions in Selenium article and we will get back to you.

Upcoming Batches For Selenium Course
Course NameDateDetails
Selenium Course

Class Starts on 23rd November,2024

23rd November

SAT&SUN (Weekend Batch)
View Details
Selenium Course

Class Starts on 25th November,2024

25th November

MON-FRI (Weekday Batch)
View Details
Selenium Course

Class Starts on 21st December,2024

21st December

SAT&SUN (Weekend Batch)
View Details
BROWSE COURSES
REGISTER FOR FREE WEBINAR Selenium Framework Explained in 60 Minutes