Multiple Exceptions (Part 3)

 Pre-requisites: Exception Handling

Multiple Exceptions 

In the last tutorial we learned to catch and handle exceptions , in this tutorial we will learn to catch and handle multiple exceptions at a time.

As we learned that we can handle exceptions using throws statement or try-catch blocks. Now we will try to learn how to catch multiple exceptions from both throws statement and try-catch blocks.

1. By using throws statement

This feature was introduced in Java 7 that we can catch multiple exceptions at the same time. The syntax for the same is as follows:

Syntax:
 public class MyClass {  
       
     // using multiThrow statement  
     public static void main(String[] args) throws Exception1, Exception2 , Exception3 {  
                // block of code   
      }  
   }  
We can catch multiple exceptions by throws statement just by separating the exceptions by commas ( , ). The block of code will catch that exception which the main body of code would throw in the future. As any one of the exceptions are caught , the compiler will jump out of the main body and would run accordingly.  


Eg:-    Here I have declared an array of int. It's length is up to five elements. Also I have used throws statement to catch  ArrayIndexOutOfBoundsException , ArithmeticException or if any other exception occurred then general Exception.
 public class MyClass {  
       
     // using multiThrow statement  
     public static void main(String[] args)  
             throws ArrayIndexOutOfBoundsException, ArithmeticException,  
             Exception {  
   
         // declaring an array of size 5 i.e index 4  
         int[] arr = new int[5];  
   
         // giving random values  
         arr[0] = 1;  
         arr[1] = 3;  
   
         /*  
          * Here 2 exceptions will arise  
          * (1) ArrayOutOfBounds because index 5 doesn't exist  
          * (2) ArithmericException because number cannot be divided by zero  
          */  
         arr[5] = 3 / 0;  //will throw ArithmeticException
         System.out.println(arr[5]);   //will throw ArrayIndexOutOfBoundsException
     }  
 }  
Output:-
 Exception in thread "main" java.lang.ArithmeticException: / by zero  
     at MyClass.main(MyClass.java:20)  
Here as the line of code which divides the number by zero is before the line of code which demands the array element in 5th index ( not present ). We get too see ArithmeticException in the ouptut window.
 
If the position of these two lines are interchanged , we would get to  see ArrayIndexOutOfBoundsException. 



2. By using try multi-catch blocks

This is also helps in catching multiple exceptions. The syntax for try multi-catch blocks is given below:

Syntax:-
         try {  
             //some code which throws exceptions   
         }  
         catch (Exception 1) {  
         }  
         catch (Exception 2) {  
         }  
         catch (Exception 3) {  
         }  
Here the code in the try block is suspicious of throwing exceptions which the catch blocks catches. You can add a number of catch blocks to a try block. As the code in the try block throws exception , the compiler searches for that exception in catch block and executes it.

Eg:- Let's see an example by using the above code but with try multi-catch block.
 public class MyClass {  
     public static void main(String[] args) {  
           
         // declaring an array of size 5 i.e index 4  
         int[] arr = new int[5];  
   
         // giving random values  
         arr[0] = 1;  
         arr[1] = 3;  
   
         /*  
          * Here 2 exceptions will arise   
          * (1) ArrayOutOfBounds because index 5 doesn't exist  
          * (2) ArithmericException because number cannot be divided by zero  
          */  
         try {  
             arr[5] = 3 / 0;  
             System.out.println(arr[5]);  
               
             //as above line will cause exception , this line would not execute   
             System.out.println("End of try block");  
               
             //catching both exceptions using try-multiCatch  
         } catch (ArrayIndexOutOfBoundsException e) {  
             System.out.println("Error: Exceeded last index !");  
         } catch (ArithmeticException e) {  
             System.out.println("Error: Calculation is not possible !");  
         } catch (Exception e) {  
             System.out.println("Some other error ocuured !");  
         }  
         finally {  
             System.out.println("Compilation was successful.");  
         }  
     }  
 }  
Output:-
 Error: Calculation is not possible !  
 Compilation was successful  
Here we get to see ArithmeticException as the line of code of number dividing by zero is before the line of code which is likely to throw ArrayIndexOutOfBoundsException. If the position of both these lines are interchanged , then we would be able to see  ArrayIndexOutOfBoundsException thrown.
 Error: Exceeded last index !  
 Compilation was successful.  

Also as the exception is thrown the line "End of try block" is also not printed out as an exception is thrown in the line before it so the compiler will skip the rest of the code and try to handle that exception. 

Some important points to remember while using try multi-catch block:-
  • A catch block cannot exist without a try statement.
  • It is not compulsory to have finally block whenever a try/catch block is present.
  • The try statement cannot be present without either catch block or finally block.
  • Any code cannot be present in between the try, catch, finally blocks.
The exceptions caught above like ArithmeticException , ArrayIndexOutOfBoundsException or IOException or FileNotFoundException are all childs of the main Parent Class Exception. 


Note:-
  • While using try multi-catch blocks one thing must be considered that we have to write the child exceptions before we catch Parent / general exception in catch block.
  • The reason behind this is that the Parent / general exception would catch any of the exceptions mentioned above so there would not be any clarity of what exceptions are thrown by our code also Java does not allow this.
  • Let's understand it by writing a code for this. I have used the above code so that you will be able to understand a bit more clearly.
 public class MyClass {  
     public static void main(String[] args) {  
   
         int[] arr = new int[5];  
   
         try {  
             arr[5] = 3 / 0;  
             System.out.println(arr[5]);  
             System.out.println("End of try block");  
   
             // catching exceptions using try-multiCatch  
         } catch (Exception e) {  
             System.out.println("Some other error occurred.");  
         } catch (ArithmeticException e) {  
             System.out.println("Error: Calculation not possible!");  
         } catch (ArrayIndexOutOfBoundsException e) {  
             System.out.println("Error: Exceeded last index!");  
         } finally {  
             System.out.println("Compilation was successful");  
         }  
     }  
 }  
When we try to execute the above code , we get the following as error:

Output:-
 Unreachable catch block for ArithmeticException. It is already handled by the catch block for Exception  
 Unreachable catch block for ArrayIndexOutOfBoundsException. It is already handled by the catch block for Exception  
Therefore , it is advised to catch the Parent / General Exception after catching its required child exceptions.


< Previous Next >