0

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 Answers3

1

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.

0

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.

Manthan
  • 93
  • 1
  • 8
  • Okay, But I can do this same with If Else condition also na... – Revanth sai Jan 12 '20 at 05:41
  • Like.. I will catch in generalized exception then in catch Block if(e.Message.equals('Attempted to divide by zero') { system.out.print("trying to divide by Zero") } – Revanth sai Jan 12 '20 at 05:48
  • Using if-else ladder in a generalized exception catch block, it will cause performance issues. If you use a generalized exception block, it has to go through a lot of checks to find the exact exception which was thrown. Moreover, on top of that, if you use if-else ladder, it again has to perform the same checks to get to the particular exception block. This is a major performance issue in itself. This is the reason why we use funneling, in which multiple catch blocks will check for one specific exception. – Manthan Jan 12 '20 at 09:40
0

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.