Multiple catch block in Java

Posted in /  

Multiple catch block in Java

Ramya Shankar
Last updated on July 11, 2022

    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 exceptions raised. If there are 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 a 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 Multiple catch block Examples 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 With Exception 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 Example without any exception handling order- People are also reading:

    Leave a Comment on this Post

    0 Comments