DEV Community

Sesha-Savanth
Sesha-Savanth

Posted on

Handling Exception in Java

What is exception handling?

An exception is an abnormal condition that disturbs the normal flow of the program. Exception handling is used in handling the runtime errors and maintains the continuity of the program.

Java exceptions

  • Checked
  • Unchecked
  • Errors

Try Block

The statements which throw an exception are to be placed under try block

It is suggested not to write unnecessary statements in the try block because the program terminates at a particular statement where an exception occurs.

Catch Block

It is used to handle the exception by declaring the type of exception within the parameter.

Single or multiple catch blocks can be used after each single try block.

Syntax of try-catch :'

 try{    
   //code that may throw an exception    
    }catch(Exception_class_Name ref){} 
Enter fullscreen mode Exit fullscreen mode

Program using Try-Catch :

public class TryCatch {

public static void main(String[] args) {  
    try  
    {  
    int arr[]= {2,4,6,8};  
    System.out.println(arr[10]);    
    }  

    catch(ArrayIndexOutOfBoundsException e)  
    {  
        System.out.println(e);  
    }  
    System.out.println("Program continues"); 
}
}
Enter fullscreen mode Exit fullscreen mode

Output

java.lang.ArrayIndexOutOfBoundsException: 10
Program continues

Program Using multiple catch blocks :

public class Multiple {

public static void main(String[] args) {  

       try{    
            int a[]=new int[5];    

            System.out.println(a[10]);  
           }    
           catch(ArithmeticException e)  
              {  
               System.out.println("Arithmetic Exception occurs");  
              }    
           catch(ArrayIndexOutOfBoundsException e)  
              {  
               System.out.println("ArrayIndexOutOfBounds Exception occurs");  
              }    
           catch(Exception e)  
              {  
               System.out.println("Parent Exception occurs");  
              }             
           System.out.println("Program Continues");    
}  
}
Enter fullscreen mode Exit fullscreen mode

Output

ArrayIndexOutOfBounds Exception occurs
Program Continues

Finally Block

The block of statements that are used to execute the important code. It is always executed whether an exception is handled or not.

Program using finally block :

public class Finally{

public static void main(String args[]){

try{

int data=25/0;

System.out.println(data);

}

catch(ArithmeticException e){
System.out.println(e);
}

finally{
System.out.println("finally block is always executed");
}

System.out.println("Program continues");

}

}
Enter fullscreen mode Exit fullscreen mode

Output

java.lang.ArithmeticException: / by zero
finally block is always executed
Program continues

Top comments (0)