Exception Handling in Java selenium webdriver

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 will not. You will see some or the other exception when you execute your scripts. When ever you see these exception regularly you will get frustrated.

When ever we develop any scripts, we will try give the best quality code that works fine. But Unfortunately, sometimes exceptions come as side effects to the scripts that we develop and fails.

Most of them especially beginners, try to handle exception as below way:

public void testCaseONE(){
    try {
        ...code which throws exceptions
    } catch (Exception ex){
        ex.printStacktrace();
    }
}

When we execute above program, if an exception is thrown, the normal program execution is suspended and control is just transferred to the catch block. The catch block then prints the exception Stacktrace and again execution of the program continues after the catch block.

So now, here comes the need of 'Exception Handling' which allows the developer to detect errors easily and prints a user friendly error message. Let us see them in detail below.

What is an Exception ?

Exception is a class which is sub class of Throwable class. In other way an Exception is an event that terminates the normal flow of program, which interrupt the entire program execution and prints a non user friendly error message. Exceptions may occur at run time or compile time.

Example:

package com.seleniumeasy.ExceptionHandling;

public class ExceptionDemo {
	public static void main(String[] args) {
		int x=0;
		int y=10;
		System.out.println(y/x);
	}
}

If we run the above program it complies well and good, but at runtime we won't get any output. The program terminates abnormally because of number divided by zero and prints message as

Exception in thread "main" java.lang.ArithmeticException: / by zero
	at com.seleniumeasy.ExceptionHandling.ExceptionDemo.main(ExceptionDemo.java:7)

Difference between Exception and Error:

Exception: Exception occurs in the programmers code which can be handled and resolvable.

---->>>>>>> Example: AritmeticException, DivideByZeroException, NullPointerException, ClassNotFoundException etc

Error: Errors are not resolvable by programmer. Error occurs due to lack of system resources

---->>>>>>> Example: Stack over flow, hardware error, JVM error etc.

The below is the exception hierarchy in java

Java Exception Hierarchy

Types of Exception: - There are two types of Exceptions:
1.Checked Exceptions
2.Unchecked Exceptions

Checked Exceptions:

Checked Exceptions are checked at compile time only, these are must and should handled by the programmer. Compiler will check at compile time whether these exceptions are handled or not if not compile time error occurs. Some of the checked exceptions are IOException, FileNotFoundExpection, ClassNotFoundException etc.

'ClassNotFoundException' Thrown when an application tries to load in a class through its string name using the below, but no definition for the class with the specified name could be found.

The 'forName' method in class Class.
The 'findSystemClass' method in class ClassLoader.
The 'loadClass' method in class ClassLoader.

When ever we try to interact with database, we try to load a JDBC driver using 'Class.forName', Check the example here to load JDBC driver when working on Database testing with selenium

'FileNotFoundExpection' and 'IOException' , When ever you try you to read or write from a File object that does not have a corresponding file on the disk you'll get IOExceptions.

Possibly there are three cases where a 'FileNotFoundException' may be thrown.

The system cannot find the file specified - Which can be resolved by specifying the correct path of the file.

Access to the file is denied - If the given file is inaccessible, when ever you try to write on the file which is 'ReadOnly', then we will get this exception. So we should make sure to have write access on the file to avoid exception.

The process cannot access the file because it is being used by another process - When ever the file is opened by any another program, then we will get this exception. Make sure close the file after accessing it.

Unchecked Exceptions:

unchecked exceptions are not checked by compiler at the time of compilation. the exceptions which are extended by RuntimeException class are all unchecked exceptions. Some of the unchecked exceptions are AritmeticException, NullPointerException etc

In selenium we see unchecked exceptions such as NoSuchElementException, StaleElementReferenceException , NoSuchWindowException, TimeoutException etc.

NoSuchElementException - Thrown by WebDriver.findElement(By by) and WebElement.findElement(By by) - When ever the element is not found in DOM, you will get this exception.

StaleElementReferenceException - This Exception occurs when driver is trying to perform action on the element which is no longer exists or not valid. You can here for more alternate ways of Handling StaleElementReferenceException

NoSuchWindowException - When ever driver tries to switch to the window which is not available, it will throw 'NoSuchWindowException'. We need to check the window id that we pass or wait for some time until the new window appears. Check here for working with windows
NoSuchFrameException - When ever driver is Unable to navigate to frame with element, it throws 'NoSuchFrameException'. Check here for Working with Frames
TimeoutException - When the Element was not displayed in the specified time. When ever we work with waits, we may see these exceptions. Check the example below:

/*Explicit wait for state dropdown field*/
    WebDriverWait wait = new WebDriverWait(driver, 10);
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("statedropdown")));

The above statement waits up to 10 seconds before throwing Exception (TimeoutException - Timed out after 10 seconds waiting for visibility of element) or if it finds the element, it will return in 0 - 10 seconds.

The exceptions that i have listed above are selenium webdriver exceptions. Here selenium webdriver class 'WebDriverException' extends 'RunTimeException' class. In turn there are sub classes like 'StaleElementReferenceException', 'TimeoutException', etc which extends 'WebDriverException'.

There is an other class which extends 'WebDriverException' is 'NotFoundException' and again this has sub classes 'NoSuchElementException', 'NoSuchFrameException' etc. Let us now look at the exception hierarchy in selenium webdriver

Selenium Exception Hierarchy

The below are the five keywords which plays the role in Exception handling : -

1. try
2. catch
3. finally
4. throw
5. throws

1. try:

try block contains the code that might raise an exception.

syntax:

try{
statements....//this code may raise an exception
}

try block Example:

try{
    int x=0;
    int y=10;
   System.out.println(y/x);// here we will get an exception as x is initialized as 0. so we should place these code in try block. 
}

2. catch:

catch block contains handling code if any exception occurs in try block. try must follows catch block. try after catch or finally is mandatory.

Syntax:

catch(Exception e){
statements....//contains handling code
}

Example:

try{
int x=0;
int y=10;
System.out.println(y/x);
}
catch(Exception e){
System.out.println("Exception has been handled" + e);//once an exception raises instead of terminating the flow of program cursor jumps to particular catch block to handle this exception and prints a user friendly 

message and the rest of code executes normally
}
System.out.println("code after try catch block");
}

when an exception raises it creates the exception object e. This object contains name of the exception class, cause and location of exception. if we already know the exception class we can directly pass the particular exception class as parameter in catch block. if we dint know what kind of exception class we can pass the Exception class as parameter as it is the parent class for all exception classes.

Exception Information displaying methods are:

1.printStackTrace(): prints the stack trace , exception name and description.
2.toString(): returns a text message describing the exception name and description.
3.getMessage(): displays the description of exception

These three methods are present in Throwable class.

package com.seleniumeasy.ExceptionHandling;

public class ExceptionMethods {
	public static void main(String[] args) {
	try{
		
	int x=0;
	int y=10;
		System.out.println(y/x);
	}
	catch(ArithmeticException ae){
		ae.printStackTrace();
		System.out.println(ae.toString());
		System.out.println(ae.getMessage());
		
	}
  }

}

output:
java.lang.ArithmeticException: / by zero
java.lang.ArithmeticException: / by zero
/ by zero
at com.seleniumeasy.ExceptionHandling.ExceptionMethods.main(ExceptionMethods.java:9)

multiple catch blocks:
try block can follow multiple catch blocks. if there is a chance of getting multiple exceptions then we go for multiple catch blocks to handle all the exceptions at once.

syntax:

try {
statements..
}
catch(){
statements..
}
catch(){
statements..
}

Example:

package com.seleniumeasy.ExceptionHandling;

public class CatchDemo {
	public static void main(String[] args) {
		 try
		  {
		   int c[]={1,2,3};// taking an array of size 3
		   System.out.println(c[2]);// here we are printing the value
		   //c[3]=5;// if we uncomment this statement exception raises and cursor jumps to catch block of ArrayIndexoutofboundsexception without executing the next line.
		   int a=10;// 
		   System.out.println(a/0) ;// if we comment the above statement of c[3]=5; this will execute and here an exception raises as ArithmeticException
		   
		  } 
		  catch(ArithmeticException ae)
		  {
		   System.out.println("number cannot divided by zero"+ae);
		  }
		  catch(ArrayIndexOutOfBoundsException aie)
		  {
		   System.out.println("array index out of bound exception"+aie);
		  }
		 catch(Exception e){
			 System.out.println(e);// this block will be executed when there were no particular exception matches
		 }
		 System.out.println("After try catch block");
	}

}

the order of parameters in catch block is child to parent.

Example:

try {
int c[]={1,2,3};
c[3]=5;
int a=10;
System.out.println(a/0) ;
}
catch(ArithmeticException ae)   {
	System.out.println("number cannot divided by zero"+ae);
  }
 catch(ArrayIndexOutOfBoundsException aie)   {
	System.out.println("array index out of bound exception"+aie);
 }
catch(Exception e){
	 System.out.println(e);
 }

and the order should not be parent to child. because once parent has caught the exception and again a child class is trying to caught the exception at the time we get a compile time error saying unreachable catch block for child exception: it is already handled by the catch block for Exception

3. finally block:

finally block is a block which executes whether exception raises or not. that is cleanup code like open files or database connections should be placed in finally block.
if we place these type of code at the bottom of try block if any exception raises in try block these code wont we executed and if we place in catch block if at all exception is not raised catch block wont be executed.

so we go for finally block.

syntax:

finally{
cleanup code;
}

finally block will executes irrespective of exception raises or not and exception handled or not. finally block appears after catch block or after try block when there is no catch block. we cannot place middle of try and catch block.

Example:

package com.seleniumeasy.ExceptionHandling;

public class FinallyDemo {
	public static void main(String[] args) {
		try{
			int x=5;
			//int x=0;
			int y=10;
			System.out.println(y/x);// here we wont get any exception because we initialize x as number . if we uncomment x=0 we get Arithmetic exception but there is no handling code now program terminates abnormally but executes code inside finally block
			}
		catch(NullPointerException ne){
			System.out.println("ne");
		}
			
		    finally{
		    	System.out.println("finally block");
		    }
			System.out.println("code after try catch block");
		}

}

finally always executes even if there is return statement in try or catch block. only the situations where finally wont be execute are if System.exit() method called, any thread interrupted and if there is any exception in finally block

example:

		try{
			System.out.println("try block");
			System.exit(0);
			System.out.println(10/0);
			
			}
		catch(Exception e){
			System.out.println(e);
			
		}
			 finally{
		    	System.out.println("finally block");
		    }
			System.out.println("code after try catch block");
		}
 

Note:
1. try always follow catch or finally block.
2. there may be nested try, multiple catch blocks for each try but there should be only one finally block.
3. In between try catch there should not be finally block.
4. try with finally is possible without catch.
5. there should not be any code in between try, catch or finally block

throw:

till now what we have seen is any exception object is automatically created and thrown. we can also create our own exception object explicitly using throw key word.

syntax:

throw new ExceptionclassName();

Example:

public static void main(String[] args) {
		throw new ArithmeticException("number divided by zero");// here we can give our own message to display 
	}

output:

Exception in thread "main" java.lang.ArithmeticException: number divided by zero
	at com.seleniumeasy.ExceptionHandling.ThrowDemo.main(ThrowDemo.java:6)

we can use throw for checked, unchecked and user defined exceptions.

Handling checked Exceptions:

If there is a chance of raising a checked exception we must and should do one of the following two things:

1. handling the exception by using try catch block or

2. specify throws clause on the method there may be a chance of raising an exception.

throws:

throws clause is used for handling checked exceptions(SQLException, FileNotFoundException, IOExceptions). Any method contains the statements that may throw an checked exception must include throws clause. Otherwise we get compile time error saying "unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown"

Syntax:

methodname() throws ExceptionName{
statements;
}

Example program without handling checked exception:

package com.seleniumeasy.ExceptionHandling;

import java.io.FileInputStream;

public class ThrowsDemo {
	public static void main(String[] args) {
		openFile("F:\\seleniumfile.txt");
	}
	public static void openFile(String name){
		FileInputStream f= new FileInputStream(name);
	}
}

In the above program we get compile time error saying "unhandled exception type FileNotFoundException" as it is checked exception there may be chance of file not existing.

Now we need to either catch the exception by using try catch block or by declaring throws clause to the method.

If suppose we don't want to deal with writing code for try catch, simply add a throws clause to the openFile method's declaration which indicates that openFile() that might throw FileNotFoundException

Example:

public class ThrowsDemo {
	public static void main(String[] args) throws FileNotFoundException {
		openFile("F:\\seleniumfile.txt");
		
	}
	public static void openFile(String name) throws FileNotFoundException{
		FileInputStream f= new FileInputStream(name);
		
	}
}

We can add more than one checked exception by separating with comma.

Example:

public static void main(String[] args) throws FileNotFoundException, IOException{
openFile("F:\\seleniumfile.txt");
}

User defined exceptions:

We can create our own exceptions called user defined exceptions or customized exceptions. In order to create our own exceptions we need to extend Runtime Exception in our class.

package com.seleniumeasy.ExceptionHandling;

public class MyOwnExceptionDemo {
	public static void main(String[] args) {
		throw new MyException("hello");
		
	}
}
	class MyException extends RuntimeException{
		public MyException(String s) {
			super(s);
			
		}
	}

NOTE: Most people often do as below, because people are lazy to consider what to catch and what to throw. Throwing Exception is a bad practice and should be avoided. Make sure you handle it and always declare the most precise exception possible which will help the developer to decide on how to deal with it.

public void someTestMethod throws Exception{
//bla bla
}
Java Tutorials for Selenium: 

Comments

Good work on explaining the exception handling. Waiting for your new post soon! Thank you for contributing to the community of Selenium WebDriver.

Very well explained.

Easy to understand and very nice explaination

My script is getting slow after using Try Catch block. Any suggestions???

Dear sir,
I have just started to learn selenium java.
I have stuck on problem of selecting a dependent(cascading) dropdown ex Country state district city.
Pls help me

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.