why to use multiple catches in exception?

102 Views Asked by At

when we can handle it in single default Exception then Why we should use Multiple Catches?

public static void main(String[] args) {  

       try{    
            int a[]=new int[5];    
            a[5]=30/0;    
           }    
           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("rest of the code");    
}  
3

There are 3 best solutions below

3
Manthan On

Please format your question properly from next time. Try to add what you have tried to solve the issue and explain your approach as much as possible.

Coming to the actual answer, you use multiple exceptions to provide specific handling mechanisms for each type of exception.

For example, if you want to handle DivideByZero exception seperately, like display a specific message to the user, you can do it by catching DivideByZero Exception, where as you can't perform the same operation using a generalized exception.

1
OM PRAKASH On

Adding to this, generalized exception can handle all the exceptions but then the message become generic. Here in we want message specific to each type of exceptions.

0
Shreeya Soni On

If you are using specific exception, let's say SqlException, it will take care of all the possible exceptions codes but in if-else ladder, you need to define all the possible scenarios and there is a high chance you might miss some of them.