Exceptions in java


Exception :

An Exception is an unplanned surprise that occurs during execution of program, the exception has power to stop the program execution.

Without a doubt exception stops the execution, but we are more powerful than exception so we can handle the exception without stopping the execution of the program.

We can obtain normal flow of program by handling the exception and we can provide more meaningful message without stopping the execution of the program.

If these exceptions are not handled properly, the remaining program will not be executed


										public class JavaException {
											public static void main(String[] args)
											{
												System.out.println("Before Exception"); 
												// below code throws Exception
												Integer intValue = new Integer("chercher tech"); 
												System.out.println("Converted value : "+intValue);
												System.out.println("After Exception");
											}
										}
										

In above program the line Integer("chercher tech") tries to convert the alphabet string into number. Converting the alphabets into number is not possible, so the program throws a java.lang.NumberFormatException.

The code present after that particular line will not be executed as exception stops the total program execution. basic-exception-java-selenium

Exception Architecture in Java


exception-architechture-java-selenium

Throwable is supermost class for Exceptions in Java, Throwable can be categorized as Error and Exception.

Error : Error is a serious condition, application must not try handle the error. Errors are mainly caused by the environment in which application is running. Errors are not checked at compile time and do not have to be (but can be) caught or handled.

Coder should not worry about errors at all in java, as errors indicate the problems with system, or environment. Below are few Errors :

  • OutOfMemoryError
  • StackOverFlowError
  • LinkageError


Exception : Exceptions are caused by application, Exceptions are derived from Throwable class. Exceptions can be categorized into two:

  • Checked Exceptions also known as Compile time Exception
  • Un-Checked Exceptions also known as Runtime exceptions


Checked Exceptions aka Compile Time Exceptions : Checked Exceptions are the exceptions that are verified at compile time, compiles itself senses that a particular code can raise exceptions.

If the code within a method throws a checked exception, then the method must either handle the exception or it must delegate the exception using throws keyword, if we donot do either of them, then compiler will not allow you to compile the program.

Below are few checked exceptions :

  • IOException
  • EOFException
  • Exception
  • MalFormedURLException
  • IntruptedException
'


Unchecked Exceptions aka Runtime Exceptions : The classes which extend RuntimeException are known as unchecked exceptions, unchecked exceptions occurs during the run time of the program. Compiler will not be able to detect the unchecked exception during compile time.

Below are few unchecked exceptions :

  • ArithmaticException
  • NullPointerException
  • IndexOutOfBoundsException
  • ClassCastException
  • ArrayIndexOutOfBoundsException
  • NoSuchElementException
  • NoSuchFrameException
  • NumberFormatException

Difference between Error and Exception

Exception and Error both are sub classes of Throwable class and both halts the program execution

User should never design an application to throw Error, but user can design an application which throws Exception

Errors in java are of type java.lang.Error whereas Exceptions in java are of type java.lang.Exception

All errors in java are unchecked type, Exceptions include both checked as well as unchecked type.

Errors happen at run time, compiler will not have knowledge of it. Checked exceptions are known to compiler where as unchecked exceptions are not known to compiler because they occur at runtime.

It is impossible to handle errors, but we can handle exceptions through try..catch..finally blocks.

Errors are mostly caused by the environment in which application is running. Exceptions are mainly caused by the application itself.

StackOverflowError, OutOfMemoryError are few examples for Error, IOException, NullpointerException are few examples for Exception.

Methods Present in Exceptions

Methods present in the Exceptions helps the user to get different details of the Exception. Below are few useful methods present in Exceptions

1. getMessage() / toString() : Returns the detailed message string, most of the time a reason why this exception occurred

2. getLocalizedMessage() : returns the localized message according the language. This is local version of getMessage(). Creates a localized description of this Exception.

Subclasses may override this method in order to produce a locale-specific message. For subclasses that do not override this method, the default implementation returns the same result as getMessage().

3. getCause() : Returns the cause of the exception or null if the cause is nonexistent or unknown.

4. getStackTrace() : This methods fetches the detailed exception details like which line caused the exception, which all are methods got affected, what is the error message and few more details.

5. printStackTrace() : This methods is similar to getStackTrace(), the only difference is this method prints the details rather than fetching the details.

Try..Catch..Finally

You might have come across situations where your program got stopped abruptly throwing some exception. Exception (recap): Exception is abnormal behavior of the code or it happens because something is wrong with our code or with our system.

Here, abnormal behavior means something or wrong with our code something like we are trying to find some element but the element is not present in webpage, program throws an exception when we try to access a file which is not present in our local system, etc..

In this tutorial you are going to learn try and catch block based only on Selenium WebDriver.

try : try block is nothing but a block which contains a certain code and that certain code may or may not behave abnormally, when the code behaves abnormally the program throws an exception but when it behaves normally it will not throw any exception.

In layman terms, try block is nothing but a room in hospital which is little sensitive and we are having patient inside the particular room, when something unexpected happens in that room the hospital will be ready to handle the situation.

When an exception occurs in try block, the code after the exception in the try block will not be executed.


									try{
										// code that we need to monitor
										}
									


catch : The catch block is nothing but a block of code, so whenever something abnormal happens in the try block the associated catch block will be executed, the catch block will be having code which will efficiently handle that particular exceptional situation

In catch block user should mention what is the exception that we should handle because we cannot handle all the exceptions as different exceptions will require a different code to handle the situation.

Catch block will not be executed if there is no exception occurs in try block


									try{
										// code that we need to monitor
										}
										catch(Exception e)
										{
											// what should we do if something abnormal occurs
										}
									


Program for simple try and catch block, there is no element present in the page with id='this-id-is-not-present'


									public static void main(String[] args) {
											// set the geckodriver.exe property
											System.setProperty("webdriver.gecko.driver", "C:/Users/user/Pictures/geckodriver.exe");
											// open firefox
											WebDriver driver = new FirefoxDriver();
											driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
											driver.get("https://chercher.tech/java/index-selenium-webdriver");
											
											try{
												// no element is present with such id
												driver.findElement(By.id("this-id-is-not-present")).click();
												
											}catch(Exception e){
												System.out.println("*************Exception Occurred***********");
												e.printStackTrace();
											}
										}
									


output-exception-selenium-webdriver Above program throws exception and the catch will be executed, the content in the catch block will be executed.


finally :Finally block is also a normal block which contains code but finally block will be executed irrespective of whether an exception occurred or not in try block

Basic rules of finally :

  • finally block will be used to perform code cleanup activities like : disconnecting browser, closing all files, closing the browser.
  • try block is must to write finally block
  • Only one finally block is allowed with try block
When finally block will not execute :

  • When System.exit() code occurs in try or in catch block
  • When JVM crashes
  • When try block is executed infinitely without breaking
  • When user stopped the execution (just for fun).


In below program, the code present in try block will throw an exception and the catch block will be executed, then finally block gets executed

Program with try..catch..finally


									public static void main(String[] args) {
										// set the geckodriver.exe property
										System.setProperty("webdriver.gecko.driver", "C:/Users/user/Pictures/geckodriver.exe");
										// open firefox
										WebDriver driver = new FirefoxDriver();
										driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
										driver.get("https://chercher.tech/java/index-selenium-webdriver");
										
										try{
											// no element is present with such id
											driver.findElement(By.id("this-id-isnot-present")).click();
											
										}catch(Exception e){
											System.out.println("*************catch block***********");
										}finally{
											System.out.println("######you have reached Finally block#####");
										}
									}
									


output-finally-block-selenium-webdriver

In below program, the code present in try block will not throw any exception so the catch block will not be executed as the catch block gets executed when there is an exception in the try block, at last finally block will be executed after the try block.


									public static void main(String[] args) {
										// set the geckodriver.exe property
										System.setProperty("webdriver.gecko.driver", "C:/Users/user/Pictures/geckodriver.exe");
										// open firefox
										WebDriver driver = new FirefoxDriver();
										driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
										driver.get("https://chercher.tech/java/index-selenium-webdriver");
										try{
											System.out.println("========try==============");
											
										}catch(Exception e){
											System.out.println("*************catch block***********");
										}finally{
											System.out.println("######you have reached Finally block#####");
										}
									}
									


output-finally-block-no-exception-selenium-webdriver

finally block without catch block : Try block expects either catch block or finally block to present or both catch and finally blocks to present but writing both catch and finally block is not mandatory.

Program for try block without catch block


									public static void main(String[] args) {
										// set the geckodriver.exe property
										System.setProperty("webdriver.gecko.driver", "C:/Users/user/Pictures/geckodriver.exe");
										// open firefox
										WebDriver driver = new FirefoxDriver();
										driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
										driver.get("https://chercher.tech/java/index-selenium-webdriver");
										try{
											System.out.println("========try==============");
											// no element is present with such id
											driver.findElement(By.id("this-id-isnot-present")).click();
											
										}finally{
											System.out.println("######you have reached Finally block#####");
										}
									}
									


finally-without-catch-selenium-webdriver In above image you can see that finally and block executed, and there is not catch block in the program.

Basic rules of try..catch..finally :

  • The code present in try block may or may not raise the exception
  • try block or catch or finally blocks cannot exits alone
  • catch or finally or both should follow try block
  • catch block is optional when finally block is present
  • finally block is optional when catch block is present
  • There is no block which executes when only an exception is not occurred in java ( but exists in python language)
  • We can't have catch or finally block without a try statement.
  • We can't write any code between try..catch..finally block.
  • try..catch blocks can be nested ( try inside another try or catch or finally)
  • We can have only one finally block with a try block.

Purpose of try..catch..finaly

The purpose of the try catch block is to continue the execution of program without stopping the execution whenever there is an exception Scenario :

1. Open browser and navigate to https://chercher.tech/java/index-selenium-webdriver
2. Click the element whose id value is ' this-id-isnot-present'
3. Close the browser.

Program without try..catch..finally


													public static void main(String[] args) {
														// set the geckodriver.exe property
														System.setProperty("webdriver.gecko.driver", "C:/Users/user/Pictures/geckodriver.exe");
														// open firefox
														WebDriver driver = new FirefoxDriver();
														driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
														driver.get("https://chercher.tech/java/index-selenium-webdriver");
														// no element is present with such id
														driver.findElement(By.id("this-id-isnot-present")).click();
														driver.close();
													}
													

The above program didnot close the browser i.e as there no element with id='this-id-isnot-present', so find element throws exception and the program stops when there is an exception.The control of the program never reaches the driver.close() command

Program with try..catch..finally


													public static void main(String[] args) {
														// set the geckodriver.exe property
														System.setProperty("webdriver.gecko.driver", "C:/Users/user/Pictures/geckodriver.exe");
														// open firefox
														WebDriver driver = new FirefoxDriver();
														driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
														driver.get("https://chercher.tech/java/index-selenium-webdriver");
														
														try{
															// no element is present with such id
															driver.findElement(By.id("this-id-isnot-present")).click();
															
														}catch(Exception e){
															// we can write the code when there is no element with given locator
															System.out.println("No element present using 'id=this-id-isnot-present'");
														}
														finally{
															driver.close();
														}
													}
													

Above code closes the browser after checking whether the element is present or not.

Think about why did I place the driver.close() in finally block ?

if you know answer enter your answer in comment section of the page

Implementing Class Constructor locator in Selenium

Exact Exception in catch block

We always should try(normal english) to write the exact exception that we are looking for in the try block.

For example in below code I am trying to find an element, click the element in selenium webdriver and I am doubtful that the element may or may not exist, if the element is not present I want to print that "element is not there".

We know that selenium webdriver throws NoSuchElementException if there is no element present with given locator.


										try{
											// no element is present with such id
											driver.findElement(By.id("this-id-isnot-present")).click();
											
										}catch(Exception e){
											System.out.println("element is not there");
										}
										

In above code, Exception e the catch block will accept all the exceptions. For instance if the element is there on the web page but the element is disabled, then selenium webdriver will throw InvalidElementStateException but our catch block will catch this exception as well, because Exception is parent class of exceptions.

If you remember our aim was to check whether element is there on the webpage or not, but we get conclusion that element is not present even though the element is present.

This is the reason why we should write specific exception in catch block to server our purpose.

Corrected code


										try{
											// no element is present with such id
											driver.findElement(By.id("this-id-isnot-present")).click();
											
										}catch(NoSuchElementException e){
											System.out.println("element is not there");
										}
										

Multiple catch blocks with try block

Java lets the user to write multiple catch block, multiple catch block is nothing but having more than one catch block per try block.

Compiler decides to which catch block should be executed if the exception mentioned in Catch block and the actual exception raised are matches.

We can write n-number of catch blocks, but make sure that you are writing the exceptions from narrow to broad. What I mean is we should write the specific exception in the first catch and little less specific or parent of specific exception in second catch block so on

Below the pyramid or narrow to broad example of NoSuchElementException
exception-pyramid-for-catch-block-selenium-webdriver


										try{
											// no element is present with such id
											driver.findElement(By.id("this-id-isnot-present")).click();
											
										}catch(NoSuchElementException e){
											System.out.println("element is not there");
										}catch (NotFoundException e) {
											System.out.println("parent of specific");
										}catch (WebDriverException e) {
											System.out.println("broader then parent");
										}catch (Exception e) {
											System.out.println("top most exception class");
										}
										

Above code deal with NoSuchElementException and its parents but we can also add random exception which donot have any relationship with other exceptions.


										try{
											// no element is present with such id
											driver.findElement(By.id("this-id-isnot-present")).click();
											
										}catch (InvalidElementStateException e) {
											System.out.println("element present but not enabled");
										}catch(NoSuchElementException e){
											System.out.println("element is not there");
										}
										


Combining multiple exceptions in One Catch block :
If we know, a particular block of code is going to throw exceptions i.e when you are not sure which exception among few exceptions and if those exceptions have any common Parent then we can use the parent exception class in catch block to handle the scenario.

But when you know that a particular code is going to throw exceptions which are not related at all then we will not have any common parent class, So in this case we have to use multiple exceptions in same catch block using | (pipe) operator.

Syntax : catch(Exception1 | Exception2 | Exception3.... e)


										try{
											// no element is present with such id
											driver.findElement(By.id("this-id-isnot-present")).click();
											// sleep method throws InterruptedException exception
											Thread.sleep(1000);
										}catch (InvalidElementStateException | InterruptedException e) {
											System.out.println("element present but not enabled");
										}
										


Basic rules for catch block :

1. Only one catch block will be executed per exception and only one exception can raise at a time
2. We should order the catch block from narrow type exception to broad.
3. We cannot have more than one catch block with a particular exception, if we try to do so the second catch block will give error saying 'not reachable code'

More than Two Browser Windows

Nested try..catch..finally blocks

When a try..catch block is present inside another try..catch block then it is called as nested try..catch. We can write a try..catch..finally inside a try block of code.

In below code inner try block throws NoSuchElementException and we have catch block with same exception to handle the exception, then finally block of the inner try will be executed.

Once inner try..catch..finally block is over, the control comes to outside catch block as there is no exception is remaining in outer try block so catch block will not be executed, but finally in outer catch block will be executed.


										public class Nested {
											public static void main(String[] args) {
												try{
													System.out.println("********Outer : try block");
													// set the geckodriver.exe property
													System.setProperty("webdriver.gecko.driver", "C:/Users/user/Pictures/geckodriver.exe");
													// open firefox
													WebDriver driver = new FirefoxDriver();
													driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
													driver.get("https://chercher.tech/java/index-selenium-webdriver");
													try{
														System.out.println("********Inner: try block");
														// no element is present with such id
														driver.findElement(By.id("this-id-isnot-present")).click();
														// sleep method throws InterruptedException exception
													}catch(NoSuchElementException e){
														System.out.println("********Inner :No such Element Exception");
													}finally {
														System.out.println("********Inner: finally block");
													}
												}catch (Exception e) {
													System.out.println("********Outer: Catch block");
												}finally{
													System.out.println("********Outer: finally block");
												}
											}
										}
										
nested-try-catch-finally-block-selenium-webdriver

We can write the nested try catch block inside catch and finally blocks as well.


										try{
											// no element is present with such id
											driver.findElement(By.id("this-id-isnot-present")).click();
											
										}catch (Exception e) {
											System.out.println("********Outer: Catch block");
											try{
												System.out.println("**********Inner: try block");
												System.out.println("title of the page is : "+ driver.getTitle());
											}catch(NotFoundException e1){
												System.out.println("********inner: catch block");
											}
										}finally{
											System.out.println("********Outer: finally block");
												}
										


Outer catch block handles exceptions raised by inner try block :
If any exception occurred in inner try block will be handled by the inner catch block, but if inner catch is not able to handle the exception then the outer catch block tries to handle the exception raised by the inner try block.

So whenever we write nested try catch block the inner catch block always will have more than one catch block by default.

In below program we will see how the outer works


										public class TwoCatches {
											public static void main(String[] args) {
												try{
													System.out.println("********Outer : try block");
													// set the geckodriver.exe property
													System.setProperty("webdriver.gecko.driver", "C:/Users/user/Pictures/geckodriver.exe");
													// open firefox
													WebDriver driver = new FirefoxDriver();
													driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
													driver.get("https://chercher.tech/java/index-selenium-webdriver");
													try{
														System.out.println("********Inner: try block");
														// no element is present with such id
														driver.findElement(By.id("this-id-isnot-present")).click();
														// sleep method throws InterruptedException exception
													}catch(InvalidElementStateException e){
														System.out.println("********Inner :No such Element Exception");
													}finally {
														System.out.println("********Inner: finally block");
													}
												}catch (NoSuchElementException e) {
													System.out.println("********Outer: Catch block");
												}finally{
													System.out.println("********Outer: finally block");
												}
											}
										}
										

In above program, the inner catch block will not be able to handle the exception thrown by the inner try block so now the exception comes to the outer exception block and outer exception is able to handle the exception as the exception raised by the inner try block is matching with the exception we mentioned in outer catch block.

From below image you can analyze the execution of above program two-catches-for-inner-try-selenium-webdriver

throws keyword in Exceptions

Throws keyword used in the methods signature, to delegate the exception to the caller.

We can handle the exception using try..catch but sometimes there will be scenario where you should not handle the exception, In such cases we must delegate the exception using throws keyword

For example you are trying to read a file based on the path passed by the user, there is chance that the file may or may not present in the local system. In this case you should not handle the exception as you donot know what the file contains in it.

So we must inform the user by delegating the exception, and it is upto end customer to handle exception or to stop the program.


										public class ThrowsKeyword {
											// this method is caller
											public static void main(String[] args) {
												try {  
													// exception is handled in caller
													String path = "C:\\PATH\\testFile.properties";
												   calledMethod(path);    
												  } catch (IOException e) {  
												   e.printStackTrace();  
												  } 
											}
											
											// this method does not handle the exception instead it delegates the exception
											 public static void calledMethod(String filePath) throws IOException{  
												// load the properties file
												 FileInputStream fis = new FileInputStream(filePath);
												 Properties prop = new Properties();
												 prop.load(fis);
											 }  
										}
										


Note : We should not try to delegate the exception all the times, sometimes we should handle the exception. We should handle the exception when we have better solution to overcome the exception.

As per me, all the Checked Exceptions must be delegated to the caller method.

throw keyword in Exceptions

So far, we are trying to catch and handle the exceptions. Before you can catch an exception, some code somewhere must throw one

Any code can throw an exception: your code, code from a package written by someone else such as the packages that come with the Java platform selenium webdriver, or the Java runtime environment.

Regardless of what/who throws the exception, it's always thrown using throw statement.

Below program throws Exception with some reason, we can throw any exception using throw keyword.


										public class SimpleThrow {
											public static void main(String[] args) throws Exception {
												System.out.println("Before throwing an exception");
												throw new Exception("Bingo,, we are throwing an exception");
											}
										}
										

Output :
throw-keyword-exception-java-selenium

Difference between throw and throws keywords

The throw keyword handover user created exception to JVM manually, throws keyword is used to delegate the responsibility of exception handling to the caller of the method

The throw keyword is followed by exception object, throws keyword is followed by the list of the exception class which can occur in the method

The throw keyword can throw only one exception object, the throws keyword can declare multiple exception classes separated by a comma or can have top most exception to delegate all the subclass exceptions.

throw key word is used in method implementation but throws is used in method signature.

Checked exception cannot be propagated using throw only but Checked exception can be propagated with throws.

Please refer the syntaxes in above topic.

Re-Throw Exception

Re-throw is nothing but throwing an Exception that we have handled

Sometimes we may need to inform the customer that we received an exception by stopping the program

But before stopping we may need to analyze the reasons or we may want to perform tasks like disconnecting from the database or closing browser in selenium. If we donot end few critical things we may face issue while reconnecting to the resources

Re-throw is not a keyword like throw, re-throw is just a concept which uses throw keyword

In below example we are throwing an exception, and handling it then re-throwing the same exception


										public static void main(String[] args) throws Exception {
		
											System.out.println("This is Re-throw example");
											try {
												throw new Exception("Bingo,, we are throwing an exception");
											} catch (Exception e) {
												System.out.println("Exception Reason :: "+ e.getMessage());
												System.out.println("we are gonna rethrow exception");
												// because we re-throwing an exception, we must add throws in method signature
												throw e;
											}
										}
										

Output :
rethrow-exception-java-selenium

FFE : Frequently Faced Exception in Java

There are n-number of exceptions are present in java but in this topic we will discuss the few Frequently faced Exceptions in Java, these exceptions are also frequently faced by selenium webdriver tester as well.

1. ArithmeticException : ArithmeticException occurs whenever our math calculations results in infinite.


										public static void main(String[] args) {
											System.out.println("Results in infinite : "+ 1/0);
										}
										

Output : arithmatic-exception-java-selenium

2. NullPointerException : NullPointerException is associated with object creation, whenever you try to access the methods inside a object without creating object.

By default all the objects will have null value, if we try to access any method without initiating the object then you will face NullPointerException.

Simple words: you get NullPointerException exception when you call any method on null object.


										public static void main(String[] args) {
											String str=null;  
											System.out.println("String length : "+str.length());
										}
										

Output : null-pointer-exception-java-selenium

3. NumberFormatException : NumberFormatException occurs when we try to convert an alphabet into a number using Integer Wropper class.


										public static void main(String[] args) {
											//converting string '10' into number 10
											int ten = Integer.parseInt("10");
											
											// converting 'abc' into number (throws exception
											int abc = Integer.parseInt("abc");
										}
										

Output : numberformatexception-java-selenium

ArrayIndexOutOfBoundsException : ArrayIndexOutOfBoundsException exception occurs when you try to access a invalid index number in a array.

For Example you have an array for 4 element but if try to access the 9th element, system throws ArrayIndexOutOfBoundsException.


										public static void main(String[] args) {
											int[] intArray = {10,20,30,40};
											// trying to access 4 element using index 3 as indexes starts from 0
											System.out.println("3rd index (4th element) : "+intArray[3]);
											//access for 9th element
											System.out.println("9th element is : "+intArray[8]);
										}
										

Output : array-index-out-of-bounds-exception-java-selenium

MalFormedURLException : MalFormedURLException is thrown when the built-in URL class encounters an invalid URL; specifically, when the protocol that is provided is missing or invalid.

Below program throws MalFormedURLException because I have not added http to the url. URL class expects fully form urls like https://chercher.tech

MalFormedURLException is Checked exception, so we have to use throws with method or we should handle the exception using try..catch


										public static void main(String[] args) throws MalformedURLException {
											URL u1 = new URL("chercher.tech"); 
										}
										

Output : MalformedURLException-java-selenium

ClassNotFoundException : ClassNotFoundException As the name suggests ClassNotFoundException in Java is a subclass of java.lang.Exception and Comes when Java Virtual Machine tries to load a particular class and doesn’t found the requested class in classpath. You need to add required jar in your classpath.

NoClassDefFoundError : NoClassDefFoundError This is caused when there is a class file that your code depends on and it is present at compile time but not found at runtime. Look for differences in your build time and runtime classpaths.

IllegalArgumentException : IllegalArgumentException Thrown when a method receives an argument formatted differently than the method expects.The only thing you must do is correct the values of the input parameters.

ClassCastException : ClassCastException Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance.


Object i = Integer.valueOf(100);
String s = (String)i;			


Solution: Be careful when trying to cast an object of a class into another class. Ensure that the new type belongs to one of its parent classes.

You can prevent the ClassCastException by using Generics, because Generics provide compile time checks and can be used to develop type-safe applications.

IllegalStateException : IllegalStateException It is used to indicate that “a method has been invoked at an illegal or inappropriate time.

Custom Exception

If you are creating your own Exceptions that is known as Custom Exception or User defined Exception. Java Custom Exception’s are used to customize the exception according to user need.

Steps to Create Custom Exception :

  • Create a java class ThisIsCustomDumbException, as best practice create custom exception class name ending with 'Exception'
  • Create constructor for the ThisIsCustomDumbException with accepting a error message as a parameter.
  • Call the super class constructor using super() keyword, the super class is nothing but Exception class.
  • If you ant to perform something then you can perform in the constructor or by creating other methods and giving them call from the constructor. We are done creating custom exception

										public class ThisIsCustomDumbException extends Exception{
											// constructor of this class
											public ThisIsCustomDumbException(String errorMessage) {
												// we have to pass message to the super class constructor
												super(errorMessage);
											}
										}
										


Steps to Use Custom Exception :

1. Create java class 'UseCustomException'
2. Create main method
3. Throw our custom exception using throw keyword.
4. System expects us either put the throw exception inside try..catch or add throws keyword with Exception class

										public class UseCustomException {
											public static void main(String[] args) throws ThisIsCustomDumbException {
												throw new ThisIsCustomDumbException("Author is dumb guy");
											}
										}
										

Output of custom Exception: custom-exception-selenium-java

Exceptions in Selenium Webdriver

There are 40 exceptions present in selenium webdriver but most of the time we face only 10-15 exceptions, this tutorial will explain about all the exception present in the Selenium.

This tutorial's scope is to discuss, what are the exception present in the selenium, when we get them and how to mitigate them.

Architecture of Webdriver Exceptions

webdriver-exception-architecture

Selenium Webdriver Exceptions


WebDriverException :
WebDriverException is the top most exception class in the selenium webdriver, it extends RuntimeException class. All selenium Exceptions are subclasses of WebDriverException class.

NotFoundException :
NotFoundException is subclass of WebDriverException, NotFoundException occurs when a thing on the DOM is not present, we may not directly receive this exception but sub-classes of this exceptions occurs during execution.

Let's discuss the Exceptions present in the NotFoundException class, then we will learn about WebDriverException.

not-found-exception-selenium-webdriver

In this tutorial I have given a sample code which causes the exception, that doesnot mean only this piece of code will raise exception. Other commands also can raise exceptions


NoSuchElementException :
Webdriver throws NoSuchElementException when there is no matching element present in the webpage.

Reasons : NoSuchElementException occurs because of one of the below reasons

  • Either Xpath you specified for the element is wrong.
  • The second reason is AJAX has not returned yet and you've already obtain NoSuchElementException
  • The page is still being rendered but you've already finished your element search because of low wait time.
  • The element is not on the page at all

Code which causes the NoSuchElementException :


									driver.findElement(By.xpath("//label/span"))
									


Exception Message:org.openqa.selenium.NoSuchElementException: Unable to locate element: //label/span


NoSuchWindowException :
selenium webdriver throws NoSuchWindowException when user tries to switch to or perform an operation on browser windows when the window is not present.

Reasons : NoSuchWindowException occurs because of one of the below reasons

1. Current window closed
2. Target window is not opened yet, but you were trying to perform operation
3. When target window has been closed but still the code tried to perform operation on the target window.


Code which causes the NoSuchWindowException :


									driver.switchTo().window("window Gu ID");
									


NoSuchFrameException :
NoSuchFrameException happens when user tries to switch to a frame which is not present at the time.

Reasons : NoSuchFrameException occurs because of one of the below reasons

1. There is no frame with given details, or the details changed during the page loading time
2. Target Frame is not actually a frame, if the locators matches with exactly with another element( as first instance).
3. We have not given enough wait time to load the frame.


Code which causes the NoSuchFrameException :


									driver.switchTo().frame("frame1");
									


NoAlertPresentException :
Selenium throws NoAlertPresentException exception when user tries to access a alert popup, which is currently not present.

Here Alert popup could be Alert Box, Confirmation Box, Prompt Box from the Javascript commands.

Reasons : NoAlertPresentException occurs because of one of the below reasons

  • When user tries to access alert which is not present in the at current time
  • When javascript is blocked in the browser
  • Not giving enough time for the alert to load
  • When alert is already closed


Code which causes the NoAlertPresentException :


									driver.switchTo().alert()
									


StaleElementReferenceException :


TimeoutException :
TimeoutException is related with explicitwait, fluentwait, pageLoadTimeOut, scriptLoadTimeout. Selenium webdriver throws the TimeoutException exception when user has defined the wait time but the element have not been found within the wait time.

Reasons : TimeoutException occurs because of one of the below reasons

  • Element is not present or given Condition is not met
  • When the given timeout is very low
  • When page takes more time to load
  • When executeAsyncScript() takes more time to return its operation


Code which causes the TimeoutException :


									WebDriverWait wait = new WebDriverWait(driver, 30);
									WebElement idElement;
									idElement = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("123")));
									


ScreenshotException :
ScreenshotException exception will be thrown when selenium fails to take screenshot of the webpage. If ScreenshotException occurs then the screenshot captured turns black

Reasons :

1. When we try to take screenshot in headless browser(phantomjs, htmlunitdriver) without enabling the screenshot functionality.


Code which causes the ScreenshotException :


									TakesScreenshot screenShot =((TakesScreenshot) driver);
									


ScriptTimeoutException :
webdriver throws ScriptTimeoutException exception when executeAsyncScript takes more time than given time limit to return the value.


JavascriptException :


UnhandledAlertException :
selenium throws UnhandledAlertException exception when user tries to perform while alert(javascript popup) is present on the page. Javascript pop ups will not allow to perform manual actions(manual testing) on the page when it is present on the page.
Reasons :

1. Javascript Popup is present on the page
2. You have written a code to accept the pop up automatically but still you are trying to handle the pop up.
3. You might have missed code to handle the pop up.

Insight : User can use getAlertText method to get the text from the alert when UnhandledAlertException exception occurs.

Compare Screenshots in selenium


UnexpectedTagNameException :
UnexpectedTagNameException occurs when user is using Select Class in selenium to perform action on the dropdown/element where the element is not formed with select html tag.
Reasons :

1. Dropdown is formed without using select tag name.
2. Html code might have changed to non-select tag after writing the test automation code.
3. If dropdown html code is specific to browser used, Sometimes code can be rendered based on the browser.


Code which causes the UnexpectedTagNameException :


									// throws the UnexpectedTagNameException
									Select dropdown = new Select( driver.findElement(By.id("//input")) 
									
									// this will not throw exception
									Select dropdown = new Select( driver.findElement(By.id("//select")) );
									


UnReachableBrowserException :
UnReachableBrowserException will be thrown when selenium webdriver is not able to connect to the browser after starting the browser.
Reasons :

  • Browser is taking more tome to invoke after the object creation
  • Browser died in between test execution, if you run large test suite.
  • Browser is not opened in virtual machines or in remote driver
  • The provided server address to RemoteWebDriver is invalid, so the connection could not be established.
  • Browser version and the driver server.exe / selenium version is not compatible
  • When you use IEdriver64.exe instead of IEdriver32.exe when the system is 32 bit architecture.
  • Note : IEDriver32.exe can be used in place of IEdriver64.exe but vice versa is not possible


NoSuchSessionException :
Selenium throws this exception when selenium is not able to connect to the browser session, this exception occurs mostly on Chromedriver
Reasons :

  • When the temp memory is running out of space, when ever we run on chrome, the chrome driver server occupies and leaves the cache file on temp directory
  • This exception occurs when you run on Docker mostly ( We run our tests inside a docker container and the docker default dev/shm size is 64mb. Increasing this resolved the "no such session" issue for us. We use docker compose so just added shm_size: 256M to the docker-compose.yml file. )
  • Browser and Driver server.exe file version mismatch
  • Problem which appears when running tests for a prolonged period


MoveTargetOutOfBoundsException :
Selenium throws MoveTargetOutOfBoundsException, when user tries to move/drag the element or the cursor outside the visible screen.
Reasons :

1. Change of screen size ( testcases are written in desktop but current execution is happening laptop, considering that desktop screen size is bigger)


Code which causes the MoveTargetOutOfBoundsException :


									Actions actions = new Actions(driver);
									actions.mouseMove( 10, 25 )
									actions.perform();
									


InvalidElementStateException :
Selenium Webdriver throws InvalidElementStateException when user tries to perform operation on a Webelement whose state is disabled.

Subclasses of this Exception gives detail explanations, the subclasses are ElementNotInteractableException, ElementNotSelectableException

Reasons :

1. When element state is disabled


Code which causes the InvalidElementStateException :


									<input type='button' disabled=true value='save'>
		
									// click the button which is disabled
									driver.findElement(By.xpath("//input[@type='button']")).click();
									
invalid-element-state-exception-selenium-webdriver


ElementNotInteractableException :
ElementNotInteractableException is throws when we try to perform operation on an element which not intereactable at the moment. ElementNotInteractableException has two subclasses which are ElementNotVisibleException, ElementClickInterceptedException.
Reasons :

1. When element size is 0 x 0 (width =0 and height =0)


Code which causes the ElementNotInteractableException :


									<input type='button' height=0px width=0px value='save'>
		
									// click the button which has width=0 and height=0
									driver.findElement(By.xpath("//input[@type='button']")).click();
									
element-not-intereactable-exception-selenium-webdriver


ElementNotVisibleException :
Selenium throws ElementNotVisibleException when user tries to perform an operation on an web element, which is present in the page but the element is currently not visible.
Reasons :

1. Clicking a element which is not visible
2. sendkeys to element which is not visible
3. Element may not be visible because there are more elements under different pages, but those page source code is still present in cache.


Code which causes the ElementNotVisibleException :


									<input type='button' hidden=true value='save'>
		
									// click the button which is hidden (not visible)
									driver.findElement(By.xpath("//input[@type='button']")).click();
									


ElementClickInterceptedException :
Indicates that a click could not be properly executed because the target element was obscured in some way, I never faced this exception in my testing life.


ElementNotSelectableException :
ElementNotSelectableException is related with Select in selenium, when user tries o select a option which is not selectable..


UnSupportedCommandException :
Webdriver has a methods gives a call to native methods present in the browser and browser reacts to the native commands. Recent times we have received updates for driver like geckodriver.exe and chromedriver.exe.

Some selenium commands are not supported by these driver and if we try to perform those commands using selenium then those goes through the driver servers and selenium throws UnSupportedCommandException if the driver server doesnot support the command
Examples : Gecko driver doesnot support Actions class


InvalidCoordinatesException :
Selenium throws InvalidCoordinatesException when user tries to move the mouse to a co-ordinate which is not valid using action class methods.
Reasons :

1. When we run our test in different size of monitors, we may face this issue.


ImeNotAvailableException :
Indicates that IME support is not available. This exception is thrown for every IME-related method call if IME support is not available on the machine.


ImeActivationFailedException :
Indicates that activating an IME engine has failed.


ConnectionClosedException :
Selenium throws ConnectionClosedException when program tries to perform operation on safari browser but where safari browser is disconnected from the selenium session.


ErrorHandler.UnknownServerException :
Exception used as a place holder if the server returns an error without a stack trace.


InvalidCookieDomainException :
webdriver throws InvalidCookieDomainException when user attempts to add a cookie under a different domain (url) than the current URL.


JsonException :
Session capabilities normally returns the values in Json and selenium parses it, JsonException occurs when user tries to get the session capabilities where the session is not created.


UnableToCreateProfileException :
We can open a browser with certain options using profiles, sometime new version of selenium driverserver or browser version may not support the profiles, during such cases UnableToCreateProfileException raises.


UnableToSetCookieException :
Webdriver throws UnableToSetCookieException when a driver fails to set a cookie.

About Author

Myself KarthiQ, I am the author of this blog, I know ways to write a good article but some how I donot have the skills to make it to reach people, would you like help me to reach more people By sharing this Article in the social media.

Share this Article Facebook
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions
  • Sathish Kumar
    StaleElementException is not explained
    Reply
  • Bibhuti Jha
    Color for checked and unchecked exception in the diagram is different 
    Reply
    • karthiQ [ admin]
      Hi Bibhuti Jha,
      
      We have corrected the color for checked and unchecked Exception.
      
      Thanks for Highlighting it.
      Reply
  • Copyright © CherCher Tech