Exception Handling in Selenium

  • Exception Handling

Exception Handling in Selenium Automation Framework

Exception Handling one of the most important and powerful mechanism to handle the run time errors so that the main process of the application will run correctly without any issues.

This article will helps you to learn about Exception handling in selenium automation framework.

Before starting into the main stuff lets brush up some of the basics here,

What is Exception?

It is defined as an event which breaks the normal process of a program, In Selenium it states as any issues or errors which stops the test case while procession before it get executed then it is an Exception.

What is an Error?

It indicates a problem which is reasonable and the application should not try to catch it.

What is Exception Handling ?

It is used to provide us a chance to process the exception object, A block of code is used to do so. It is a resolution for the exceptions which appears during the process.
Types of Exceptions in Selenium
The below listed are the exceptions which occurs during the course of testing.
• NoSuchElementException
• StaleElementReferenceException
• TimeoutException
• ElementNotVisibleException
• ElementNotSelectableException

Handling the Exceptions


Try/Catch:

Try/Catch keywords are the one which is used to handle the exceptions.
try
{
// Some code
}catch(Exception e)
{// Code for Handling the exception
}
try
{
// Some code
}catch(Exception e){
// Code for Handling the exception
}

This Try/Catch code is placed in the code where the exception occurs.

What if there is many exceptions, then handle it with Multiple catch blocks,

try
{
//Some code
}catch(ExceptionType1 e1)
{
//Code for Handling the Exception 1
}catch(ExceptionType2 e2){
//Code for Handling the Exception 2
}

Exception Handling in Selenium

Time out Exception using Selenium WebDriver

try{
myTestDriver.findElement(By.xpath(“//*[@id=’register’]”)).click();
}catch (TimeoutException toe) {
wait.until( ExpectedConditions.elementToBeClickable(By.xpath(“//*[@id=’register’]”)));
myTestDriver.findElement(By.xpath(“//*[@id=’register’]”)).click();
}catch (Exception e) {
Log.error(“Register element is not found.”);
throw(e);
}
}

Previous Tutorials: