There are numerous exception in selenium webdriver, few of the common exceptions are –

  • NoSuchElementException
  • NullPointerException
  • NoSuchWindowException
  • NoSuchFrameException
  • NoAlertPresentException
  • InvalidSelectorException
  • ElementNotSelectableException
  • TimeoutException
  • ElementNotVisibleException
  • StaleElementReferenceException

Refer below piece of code-

package TestPackage;

public class Exception_Example {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int a = 2;
		int b = 0;
		int c;
		c=a/b;
		System.out.println("**Value of c= a/b**"+c);
	}
}

Output of above code is- It says arithmetic exception at line number 10.

Exception in thread “main” java.lang.ArithmeticException: / by zero
at TestPackage.Exception_Example.main(Exception_Example.java:10)

Now how to handle it, Can it be handled by placing code under try-catch block? Anser is yes exception message will be handled but there will not be any output.

The recommendation is, it is not necessary to use try-catch to handle an exception, handle your exception programmatically. like below code-

package TestPackage;

public class Exception_Example {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
			int a = 2;
			int b = 0;
			int c = 0;
			if(b==0)
			{
				System.out.println("**Denominator is Zero**");
			}
			else
			{
				c=a/b;
			}
			
			System.out.println("**Value of c= a/b**"+c);
				
	}
}

The output of the above code-

Denominator is Zero
Value of c= a/b0

Summary

Summarizing above, it is not necessary to use try-catch to handle exceptions in java, try to handle it by writing code(in a way such that it can handle unwanted outcome).

We can classify exceptions/errors in selenium automation in 3 categories, Most(almost ~90%) of the selenium exceptions/failure occurred because of 2 key reasons-

1- Sync Issues- Handle sync using Implicit/Explicit wait or custom sync methods to handle this.

2- Locater Issue- Use robust locators

3- Script/java/other language issues- Or better, lack of exception handling methods in the framework.

While designing your Test automation suite/framework if above 3 points are analyzed carefully then most of the failure will be handled.

Happy Automating!!!