All IT Courses 50% Off
Selenium Tutorials

Selenium Exception Handling

Selenium Exception handling is the process or a mechanism that detects and resolves the runtime exceptions and communication errors in Selenium.

An Exception is a standard term used by software programmers regardless of any programming language used to write the code. Exception, as the name suggests, is the unusual event or an uncommon case, which disrupts the normal flow of program execution.

There are various reasons for the happening of exceptions that indicates the halt in the program flow. An exception object is created whenever an exception is encountered, which contains debugging information like the type of Exception, the line number, the method hierarchy. Once an exception object is created and is handed over to the runtime environment, this process is termed as “Throwing the Exception.”

The Exceptions are classified mainly in two types: Checked Exception and Unchecked Exception.

  • Checked Exceptions: These exceptions are mainly handled while we write the code itself before the compilation of the code, and hence they are explored at compile time.
  • Unchecked Exceptions: Unchecked exceptions get thrown at run time and are more catastrophic than Checked Exception.

What is Exception Handling in Selenium?

Selenium Exception handling is the process or a mechanism that detects and resolves the runtime exceptions and communication errors in Selenium.

10 Common Exceptions in the Selenium WebDriver:

Below are a few standard Selenium exception handling that are faced while running a test:

  1. ElementNotVisibleException: Despite the element being present in the DOM, it is not visible (can not be interactive). For instance, elements defined in HTML with type =”hidden”.
  2. ElementNotSelectableException: An element is disabled (i.e., can not be clicked/selected) despite being present in the DOM.
  3. NoSuchElementException: When the Webdriver is not able to determine the elements during runtime, i.e., the FindBy method cannot find a particular component.
  4. NoSuchFrameException: When the Webdriver attempts to switch to an invalid frame, which is unavailable.
  5. NoAlertPresentException: When the Webdriver is trying to switch to an invalid alert, which is unavailable.
  6. NoSuchWindowException: When the Webdriver is trying to switch to an invalid window, which is unavailable.
  7. StaleElementReferenceException: The referenced element that is no longer present on the DOM page (a reference to a component is now Stale). For instance, the item belongs to a different frame than the current one, or the user has navigated away to another page.
  8. SessionNotFoundException: When the Webdriver is acting immediately after ‘quitting’ the browser.
  9. TimeoutException: When the command did not complete in the specified time. For instance, the element didn’t display at the specified time. This is especially encountered while working with waits.
  10. WebDriverException: When the Webdriver is acting immediately after ‘closing’ the browser.

How to Handle an Exception?

Try/Catch: A method will catch an exception using a combination of the try and catch keywords. Try is the block’s start, and Catch is at the end of the try block for handling the exceptions. A try/catch block is always placed around the code that may generate an exception. Code within a try/catch block is termed to as protected code, and the syntax for using try/catch looks like the following:

try
 {
 // Some code 
 }catch(Exception e){ 
 // Code for Handling an exception
 }

Multiple Catch blocks: A try block may be followed by multiple catch blocks. As said earlier, there are multiple exceptions, and you can expect more than one type of exception on a single code block and one like to handle each type of exception separately with a separate block of code. The syntax for multiple catch blocks will look like the following:

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

Throw: Sometimes, we want to generate exceptions explicitly in our code; for instance, in Selenium Automation Framework, most of the time we display self-written logs, once we are able to catch an exception we need to throw that exception back to the system so that the test case can be terminated. The throw keyword is always used to throw an exception to the runtime to handle it.

Throws: When you are throwing an exception in a method and not handling it, you need to use the keyword throws in the method to allow the caller program know the exceptions thrown by the method.

public static void anyFunction() throws Exception{ 
    try{ 
 // write the code here    
  }catch (Exception e){
  // Now throw an exception back to the system
         throw(e);
         }
     }

Multiple Exceptions: You can provide multiple exceptions in the throws clause.

public static void anyFunction() throws ExceptionType1, ExceptionType2{
  try { 
 //Some code  
 }catch(ExceptionType1 e1){  
 //Code for Handling the Exception 1 
 }catch(ExceptionType2 e2){ 
 //Code for Handling the Exception 2 
 }

Finally: The finally keyword is used for creating a block of code that follows a try block. A finally block always executes, whether or not an exception has occurred.

try
{
  //Protected code
}catch(ExceptionType1 e1)
{
  //Catch block
}catch(ExceptionType2 e2)
{
  //Catch block
}catch(ExceptionType3 e3)
{
  //Catch block
}finally
{
  //The finally block always executes.
}

Exception Handling in Selenium:

Your Selenium test must be able to fail, but not because of the exceptions that are thrown. If your test is failing because of exceptions, then you have no exception handling. By doing this, you do not have the opportunity to clean up the WebDriver object at the end of the test.

The tests must be failing under your terms only; for instance, you should never be getting exceptions such as NullPointerException, but if you are getting such as ElementNotFoundException, it is also a good idea for catching the exception, stop the further execution and Logically end your test.

Example 1: We do not use any Page Object Factory, but we use our own Page Object Pattern, and you always print error logs and take a screenshot of any exception you encounter. Please look at the code below:

public static WebElement btn_ReportCategory(WebDriver driver) throws Exception{ 
        try{ 
            WebElement element = driver.findElement(By.linkText("+ Report Categories")); 
        }catch (Exception e){ 
 // Printing logs for my report 
            Log.error("Report Category button element is not found."); 
 // Taking screenshot for defect reporting 
 Utils.captureScreenShot(); 
            throw(e); 
        } 
 // This will return the Web Element in case of no Exception 
        return element; 
    }

Example 2: TimeoutException using the 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); 
    } 
}

Example 3: Let us assume that in Selenium WebDriver, you want to verify the presence of an element on the page. You would not be able to done this with an element locator because if the element is present, your locator must work, and you will easily be able to print that the element is present, but in case when your element is not present on the page, your locator should fail and throw the exception. This case can be easily handled with the self-written function.

public static boolean verifyObjectPresent(WebDriver driver) { 
     try { 
      driver.findElement(By.linkText("+ Report Categories")); 
      return true; 
     } catch (Exception e) {  
      return false; 
     } 
 }

You can also use the below methods for displaying Exception Information:

  • printStackTrace(): It will print the stack trace, name of the exception, and other useful descriptions.
  • toString(): It will return a text message describing the exception name and description.
  • getMessage(): It will display the description of the exception.
Facebook Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Articles

Back to top button
Close
Close

Get Selenium Training Online
Course Now at 50%OFF!

Offer valid for 1st 20 seats only, Hurry up!!

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

H2kinfosys will use this information to be in touch with you for providing updates.