java 7 catch multiple exceptions

Java 7 provides the facility to catch multiple type exceptions in a single catch block to optimize code. We can use vertical bar or pipe (|) to separate multiple exceptions in catch block.

Multiple exceptions handling before Java 7

package com.w3schools;

public class MultipleExceptionHandling {
	public static void main(String args[]){
		try{    
            int array[] = new int[5];    
            array[5] = 20/0;    
        }    
        catch(ArithmeticException e){  
        	System.out.println("ArithmeticException catch block");
            System.out.println(e.getMessage());  
        }    
        catch(ArrayIndexOutOfBoundsException e){ 
        	System.out.println("ArrayIndexOutOfBoundsException catch block");
            System.out.println(e.getMessage());  
        }    
        catch(Exception e){  
        	System.out.println("Exception catch block");
            System.out.println(e.getMessage());  
        }    
	}
}

Output

ArithmeticException catch block
/ by zero

Multiple exceptions handling after Java 7

package com.w3schools;

public class MultipleExceptionHandling {
   public static void main(String args[]){
       try{    
            int array[] = new int[5];    
            array[5] = 20/0;    
        }    
        catch(ArithmeticException | ArrayIndexOutOfBoundsException e){  
            System.out.println(e.getMessage());  
        }     
   }
}

Output

/ by zero

Note: In case of catching multiple exceptions, if we are using super class, don’t use child class.

package com.w3schools;

public class MultipleExceptionHandling {
	public static void main(String args[]){
		try{    
            int array[] = new int[5];    
            array[5] = 20/0;    
        }    
        catch(Exception | ArithmeticException | ArrayIndexOutOfBoundsException e){  
            System.out.println(e.getMessage());  
        }     
	}
}

Output

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
	The exception ArithmeticException is already caught by the alternative Exception
	The exception ArrayIndexOutOfBoundsException is already caught by the alternative Exception

	at com.w3schools.MultipleExceptionHandling.main(MultipleExceptionHandling.java:9)
Please follow and like us:
Content Protection by DMCA.com