How To Handle Exception Through Selenium Web Driver

An exception is an event in software development language, which terminates the program, if the worst program scenarios are not handled properly. Basically in general programming language, we can also say that Exception is a class which is sub class of Throwable class. An exceptions can disturb our script workflow or can terminate the program. An exception may occur during program execution (run time) or compiling time. There can be many reasons of an exception like open non existing file, network connection relation problems, and missing class file at time of page/function load etc. To resolve this problem, we use exception handling concept which allows the developer/tester to detect errors easily and prints a user friendly error message and save our program from cessation.

Here is an example of how to handle exception through Selenium Web Driver, especially in beginner’s stage:

public void test(){
try {
...write code which throws exceptions
}catch ( exceptionvariable){
exceptionvariable.printStacktrace();
}
}

When we execute our program including exception handling code, so if an exception is thrown, that moment our program execution will get suspended and program control will switch to the catch block. It will print exception stacktrace message and then execute program after the catch block.

On a broader level, we can classify exceptions in three types:

  1. Error: Error cannot be resolved by programmer. Error occurs due to lack of system resources like hardware error, JVM error, stack over flow etc.
  2. Checked Exception: Except Runtime exceptions, all kind of exceptions are known as checked exceptions. For instance the compiler checks for exceptions during compilation to see whether the developer has resolved them or not. If such exceptions are not declared or handled in the program, system will show compilation error like ClassNotFoundException, NoSuchFieldException, EOFException, IllegalAccessException etc.
  3. Unchecked Exception: All runtime exceptions are considered as unchecked exceptions. These exceptions are not included in any Function/method’s throws list because compiler does not check to confirm that a method handles or throws runtime exceptions. Like NoSuchElementException, ArithmeticException, StaleElementReferenceException, ArrayIndexOutOfBoundsException, NullPointerException etc.

The following keywords play a vital role in exception handling:

  1. Try block: covers the program code that might raise an exception. Try must be followed by catch or finally block or both.
  2. Catch: if any exception occurs in try block, catch will take care of exception with respective handling code. A single try block can have multiple catch statements allied with it, however make sure that each catch block will be defined for only one exception class only. Suppose if try block is not throwing any exception, then catch block will be completely ignored and the program continues.
  3. Finally block : a kind of cleanup code which will be executed regardless of exception arises or not and any existing exception handled or not. Finally block will be written after catch block or after try block with no catch block or nested try, multiple catch blocks for each try. There must not be any program code in-between try, catch and finally block. There should be only one finally block in the last of all try-catch statements.
    try {
    statements..
    }
    catch(){
    statements..
    }
    finally{
    write cleanup code here ;
    }
    
  4. Throws used to declare checked exceptions like SQLException, IOExceptions, FileNotFoundException, etc. It gives information to the developer that there may occur an exception so it would be better to provide the exception handling code to maintain normal program flow.
    Throws can be used in two ways:

    • When the developer caught the exception i.e. handle the exception using try/catch.
    • When the developer declares the exception i.e. specifying throws with the method.
    public class Throwsfunction {
    	public static void main(String[] argu) throws FileNotFoundException {
    		findaFile("File name with complete path");
    	}
    	public static void openFile(String anyname) throws FileNotFoundException{
    		FileInputStream finput= new FileInputStream(anyname);
    	} OR
    	public static void main(String[] args) throws FileNotFoundException, IOException{
    //We can add more than one checked exception by separating with comma
    		findaFile("File name with complete path");
    	}
    }
    
  5. Throw keyword is slightly different from throws keyword and is beneficial to throw an exception explicitly when required. We can also create our own exception object explicitly using “throw” keyword.
    Syntax like: throw new ExceptionclassName();
    public static void main(String[] argus) {
    		throw new ArithmeticException("");// here we can provide our own message to display
    	}
    

    Few other important features to handle exceptions in Selenium Web Driver:

    1. Make a habit to always print error logs and take screenshot of any exception
      public static WebElement Imagedownload(WebDriver driver) throws Exception{
               try{
                   WebElement element = driver.findElement(By.linkText(“Download"));
               }catch (Exception exception){
       			// Printing error log
                   Log.error("Image download button is not found on the page.");
       			// Take screenshot of defect for issue reporting
       			Utils.captureScreenShot();
       		throw(exception);
               }
       		// this will return the element in case of no exception occur
               return element;
           }
      
    2. Use TimeoutException when an application takes time to execute any action
      try {
      myDriver.findElement(By.xpath(“Xpath of element")).click(); //Provide Xpath of the object
      } catch (TimeoutException toe) {
      wait.until( ExpectedConditions.elementToBeClickable(By.xpath(""))); //Provide Xpath of the object
      myDriver.findElement(By.xpath("Xpath of Element]")).click(); //Provide Xpath of the object
      } catch (Exception exception) {
      Log.error("
      
    3. There are few methods in Throwable class to display information of exception:
      • printStackTrace() method will print the stack trace, an exception name and description.
      • toString() method will return a text message telling about the exception name and description.
      • getMessage() method will show exception details
        public class ExceptionMethodDisplay {
        	public static void main(String[] argu) {
        	try{
        	Int number=100;
        	System.out.println(number/0); here system will show Arithmetic Exception
         	}
        	catch(ArithmeticException exception){
           		System.out.println("Invalid process: number cannot divided by zero"+ exception);
        		exception.printStackTrace();
        		System.out.println(exception.toString());
        		System.out.println(exception.getMessage());
        	}
          }
        

While programming the code, we need to keep in mind all the possible exceptions and also try to consider what to catch and what to throw. Always make a good practice to declare the most accurate exception potential which will help the developer to decide on how to deal with it. Also remember that Throwing Exception is not a good practice and should be avoided.How-to-Handle-Exception-Through-Selenium-Web-Driver
An exception is an event in software development language, which terminates the program, if the worst program scenarios are not handled properly. Basically in general programming language, we can also say that Exception is a class which is sub class of Throwable class. An exceptions can disturb our script workflow or can terminate the program. An exception may occur during program execution (run time) or compiling time. There can be many reasons of an exception like open non existing file, network connection relation problems, and missing class file at time of page/function load etc. To resolve this problem, we use exception handling concept which allows the developer/tester to detect errors easily and prints a user friendly error message and save our program from cessation. Here is an example of how to handle exception, especially in beginner’s stage:

public void test(){
try {
...write code which throws exceptions
}catch ( exceptionvariable){
exceptionvariable.printStacktrace();
}
}

When we execute our program including exception handling code, so if an exception is thrown, that moment our program execution will get suspended and program control will switch to the catch block. It will print exception stacktrace message and then execute program after the catch block. On a broader level, we can classify exceptions in three types:

  1. Error: Error cannot be resolved by programmer. Error occurs due to lack of system resources like hardware error, JVM error, stack over flow etc.
  2. Checked Exception: Except Runtime exceptions, all kind of exceptions are known as checked exceptions. For instance the compiler checks for exceptions during compilation to see whether the developer has resolved them or not. If such exceptions are not declared or handled in the program, system will show compilation error like ClassNotFoundException, NoSuchFieldException, EOFException, IllegalAccessException etc.
  3. Unchecked Exception: All runtime exceptions are considered as unchecked exceptions. These exceptions are not included in any Function/method’s throws list because compiler does not check to confirm that a method handles or throws runtime exceptions. Like NoSuchElementException, ArithmeticException, StaleElementReferenceException, ArrayIndexOutOfBoundsException, NullPointerException etc.

The following keywords play a vital role in exception handling:

  1. Try block: covers the program code that might raise an exception. Try must followed by catch or finally block or both.
  2. Catch: if any exception occurs in try block, catch will take care of exception with respective handling code. A single try block can have multiple catch statements allied with it, however make sure that each catch block will be defined for only one exception class only. Suppose if try block is not throwing any exception, then catch block will be completely ignored and the program continues.
  3. Finally block : a kind of cleanup code which will be executed regardless of exception arises or not and any existing exception handled or not. Finally block will be written after catch block or after try block with no catch block or nested try, multiple catch blocks for each try. There must not be any program code in-between try, catch and finally block. There should be only one finally block in the last of all try-catch statements.
    try {
    statements..
    }
    catch(){
    statements..
    }
    finally{
    write cleanup code here ;
    }
    
  4. Throws usedto declare checked exceptions like SQLException, IOExceptions, FileNotFoundException etc. It gives an information to developer that there may occur an exception so it would be better to provide the exception handling code to maintain normal program flow. Throws can be used in two ways:
    1. When developer caught the exception i.e. handle the exception using try/catch.
    2. When developer declares the exception i.e. specifying throws with the method.
    public class Throwsfunction {
    	public static void main(String[] argu) throws FileNotFoundException {
    		findaFile("File name with complete path");
    	}
    	public static void openFile(String anyname) throws FileNotFoundException{
    		FileInputStream finput= new FileInputStream(anyname);
    	} OR
    	public static void main(String[] args) throws FileNotFoundException, IOException{
    //We can add more than one checked exception by separating with comma
    		findaFile("File name with complete path");
    	}
    }
    
  5. Throw keyword is slightly different from throws keyword and is beneficial to throw an exception explicitly when required. We can also create our own exception object explicitly using “throw” keyword.
    Syntax like: throw new ExceptionclassName();
    public static void main(String[] argus) {
    		throw new ArithmeticException("");// here we can provide our own message to display
    	}
    

    Few other important features to handle exceptions:

    1. Make a habit to always print error logs and take screenshot of any exception
      public static WebElement Imagedownload(WebDriver driver) throws Exception{
               try{
                   WebElement element = driver.findElement(By.linkText(“Download"));
               }catch (Exception exception){
       			// Printing error log
                   Log.error("Image download button is not found on the page.");
       			// Take screenshot of defect for issue reporting
       			Utils.captureScreenShot();
       		throw(exception);
               }
       		// this will return the element in case of no exception occur
               return element;
           }
      
    2. Use TimeoutException when application takes time to execute any action
      try {
      myDriver.findElement(By.xpath(“Xpath of element")).click(); //Provide Xpath of the object
      } catch (TimeoutException toe) {
      wait.until( ExpectedConditions.elementToBeClickable(By.xpath(""))); //Provide Xpath of the object
      myDriver.findElement(By.xpath("Xpath of Element]")).click(); //Provide Xpath of the object
      } catch (Exception exception) {
      Log.error("
      
    3. There are few methods in Throwable class to display information of exception:
      • printStackTrace() method will print the stack trace, an exception name and description.
      • toString() method will return a text message telling about the exception name and description.
      • getMessage() method will show exception details
        public class ExceptionMethodDisplay {
        	public static void main(String[] argu) {
        	try{
        	Int number=100;
        	System.out.println(number/0); here system will show Arithmetic Exception
         	}
        	catch(ArithmeticException exception){
           		System.out.println("Invalid process: number cannot divided by zero"+ exception);
        		exception.printStackTrace();
        		System.out.println(exception.toString());
        		System.out.println(exception.getMessage());
        	}
          }
        

While programming the code, we need to keep in mind all the possible exceptions and also try to consider what to catch and what to throw. Always make a good practice to declare the most accurate exception potential which will help the developer to decide on how to deal with it. Also remember that Throwing Exception is not a good practice and should be avoided.[:]