Exception Handling in Java

  • (4.0)
  • | 63 Ratings |
  • Last Updated February 08, 2019

Exception handling is a powerful mechanism of Java to take care of the runtime errors without interrupting normal flow of the program. 

What is an Exception?

An exception is an abnormal or unwanted condition which occurs during the program execution and disrupts the flow of program.

The core advantage of exception handling is to maintain the flow of the program. Let us understand this by one example:

Consider a program is of 10 expressions like shown below:

Expr 1;  
Expr 2;  
Expr 3;  
Expr 4;  
Expr 5;
Expr 6;  //exception occurs  
Expr 7;  
Expr 8;  
Expr 9;  
Expr 10;  

Now if there is an exception occurring at expression 6, the rest of the code after that will not be executed. In this case expr7 to 10 will be ignored. Now if we include exception handling in our code, rest of the expressions will be executed. 

Exception Vs Error

Exception: Exception occurs in the program which can be resolved and handled in program code. For There are 2 types of exceptions available:

  1. Checked Exception: Checked exceptions are verified at compile time only. They must be handled by programmer in code. If not, then we will be getting compiler error. Some of the checked exceptions are SQLException, FileNotFoundException, IOException etc.  
  2. Unchecked Exception: Unchecked exceptions are not checked by compiler while compiling the code.  They are checked at runtime only. For example, NullPointerException ,ArithmeticException, ArrayIndexOutOfBoundsException etc.  In Selenium we will be handling unchecked exceptions like StaleElementReferenceException,  TimeoutException, NoSuchWindowException, NoSuchElementException etc.

Error: Error cannot be resolved by a programmer. They are irrecoverable. Error is also one type of unchecked exception. They occur due to some scarcity of system resources. For Example: JVM Error, Stack over flow, hardware error etc.

Exception Keywords in Java

Below 5 keywords are used to handle exceptions in Java.

  1. try: The “try” keyword is the indicator of a block where we need to put our exception code. The “try” block cannot be used alone. It must be accompanied with catch or finally.
  2. catch: The “catch” block cannot be used standalone. It must be used along with “try” block. It is used to handle the exception. Multiple catch blocks are possible in Java to handle multiple types of exceptions. 
  3. finally: The “finally” block is used to execute the cleanup code in the program. It will be executed irrespective of whether the exception is handled or not. There should be only one “finally” block even if code is having multiple try...catch block.
  4. throw: The “throw” keyword is entered to throw a manual exception. 
  5. throws: The "throws" keyword is used to declare exceptions. It is not used to throw an exception. It indicated the possibility of exception in the method. It must always be used with method signature. 

Exception Handling Example

Let us go through different examples of Exception Handing in Java.

  • try…catch block: In this example, we can see that after handling exception, control is being passed to the next statement written after try…catch block.
public class DemoException{  
public static void main(String args[]){  
   int d=10/0;  
 catch (ArithmeticException e)
    System.out.println("Catch block"+ e);
 System.out.println("rest of the code");  


Catch block Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code
  • try…catch…finally block: As discussed, we can have one try block followed by multiple catch blocks to handle multiple types of exceptions. The “finally” block is executed even if exception rises or not.
public class DemoException {
    public static void main(String[] args) {
           int a[]={4,8,9};
           //a[3]=1;// if this line is uncommented then this statement will raise exception of type ArrayIndexOutobouncException. In this case control will got to that block which is handling this exception
           int x=10;
          catch(ArithmeticException e1)
           System.out.println("number cannot divided by zero"+e1);
          catch(ArrayIndexOutOfBoundsException e2)
           System.out.println("array index out of bound exception"+e2);
          catch(Exception e)
             System.out.println(e);// when any matching exception is not handled then control will come to this block.
              System.out.println("in finally block"); //this will be executed even if exception is handled or not.
         System.out.println("After try catch finally block");


number cannot divided by zerojava.lang.ArithmeticException: / by zero
in finally block
After try catch block
  • throw: The “throw” keyword is entered in code to throw an exception manually by a programmer. In below code we are throwing an arithmetic exception by giving our own message to display.
public class throwDemo{
public static void main(String[] args) {
        throw new ArithmeticException("throwing  arithmetic exception"); 


Exception in thread "main" java.lang.ArithmeticException: throwing  arithmetic exception at throwDemo.main(
  • throws :The “throws” keyword is used with method signature to mention that this method might throw exception. To avoid dealing with try and catch block, we can simply write throws expression to avoid any compile time error. 
public class ThrowsExceptionDemo {
    public static void main(String[] args) throws FileNotFoundException {
        openF("G:	est.txt");
    public static void openF(String fname) throws FileNotFoundException{
        FileInputStream f= new FileInputStream(fname);

Java’s Built-In Exceptions

Java has some in-built in exception classes inside the standard package java.lang. You might have faced some of those exceptions till now.  These unchecked exceptions must be included in any method’s throw list if that method is supposed to trigger that exception and it is not handled there.

Below is the list of in-built unchecked and checked exceptions provided by Java with its meaning.

Unchecked Exception Meaning
ArithmeticException Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds
IllegalArgumentException Illegal argument used to invoke a method.
IndexOutOfBoundsException Some type of index is out-of-bounds.
NullPointerException Invalid use of a null reference.
NumberFormatException Invalid conversion of a string to a numeric format.
StringIndexOutOfBounds Attempt to index outside the bounds of a string.
TypeNotPresentException Type not found.
Checked Exception Meaning
ClassNotFoundException Class not found
IllegalAccessException Access to a class is denied
InstantiationException Attempt to create an object of an abstract class or interface.
InterruptedException One thread has been interrupted by another thread
NoSuchFieldException A requested field does not exist.
NoSuchMethodException A requested method does not exist.

Subscribe For Free Demo

Free Demo for Corporate & Online Trainings. Protection Status