Multiple Catch Blocks Java Example Program


Syntax

try {
    // Do something
} catch (Exception1 ex) {
    // Do something with caught exception
} catch (Exception2 ex) {
    // Do something with caught exception
}

Multiple Catch Blocks Example Program

public class MultipleCatchBlocks {
    public static void main(String args[]){ 
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the divisor to divide 100 : ");
        int divisor = scanner.nextInt();
        try{ 
            int[] array=new int[10]; 
            int result = 100/divisor;
            array[10]=result; 
        }catch(ArithmeticException e){
            System.out.println("Arithmetic exception has occurred");
        }catch(ArrayIndexOutOfBoundsException e){
            System.out.println("Array Index Out Of Bounds Exception has occurred");
        }catch(Exception e){
            System.out.println("Common exception has occurred");
        }
    }
}

Sample Output 1

Enter the divisor to divide 100 : 
10
Array Index Out Of Bounds Exception has occurred

Sample Output 2 

Enter the divisor to divide 100 : 
0
Arithmetic exception has occurred