Multiple catch block

    Java allows you to use more than one catch block that must be followed after the try block. Also, every catch block should have a different exception handler to handle different type of exception raised. If there is two or more catch block having the same exception handler then the JVM will get confused with block to execute and will result in an error.

    At a time only one catch block will get executed. All the catch block should be ordered with particular exception handler.

    Example-

    import java.util.regex.*;  
    
    public class Simple{  
        public static void main(String args[]){  
           try{  
               int data=100/0;  
           }  
    
           catch(ArithmeticException e){  
                System.out.println(e);  
            } 
    
           catch(ArrayIndexOutOfBoundsException e){  
                 System.out.println("ArrayIndexOutOfBounds");  
            }    
           catch(Exception e){  
                 System.out.println("Parent Exception");  
            }             
            System.out.println("code");    
          }
    }

    Output-

    Example-

    import java.util.regex.*;  
    
    public class Simple{  
        public static void main(String args[]){  
           try{    
               String s=null;  
               System.out.println(s.length());  
              }    
    
           catch(ArithmeticException e){
               System.out.println("Arithmetic Exception");  
              }    
    
           catch(ArrayIndexOutOfBoundsException e){
                System.out.println("ArrayIndexOutOfBounds Exception");  
              }    
    
           catch(Exception e){
                System.out.println("Parent Exception");  
              }             
           System.out.println("rest code");    
        }  
    }  

    Output-

    Example without any exception handling order-

    import java.util.regex.*;  
    
    public class Simple{  
       public static void main(String args[]){  
         try{    
            int a[]=new int[10];    
            a[10]=30/0;    
         }    
    
         catch(Exception e){System.out.println("completed");}    
         catch(ArithmeticException e){System.out.println("task1 completed");}    
         catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}    
         System.out.println("rest code");    
       }    
    }    

    Output-