Skip to main content

Practical-41

Write a java program which uses Multiple catch Blocks.


Introdution

Java language supports multiple catch blocks which help to catch different exceptions that can arise during the execution of a program’s code. The catch keyword can be used to catch and handle an exception when the code throws an exception. Each multiple catch block must be followed by a finally block. This finally block can be used to execute code after the method has finished.

Code

public class MultipleCatch {
public static void main(String args[]){
try{
int a[]=new int[7];
a[4]=30/0;
System.out.println("First print statement in try block");
}
catch(ArithmeticException e){
System.out.println("Warning: ArithmeticException");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Warning: ArrayIndexOutOfBoundsException");
}
catch(Exception e){
System.out.println("Warning: Some Other exception");
}
finally{
System.out.println("finally block executed");
}
System.out.println("Out of try-catch-finally block...");
}
}

Output

Warning: ArithmeticException
finally block executed
Out of try-catch-finally block...
Explanation

This code example demonstrates how to handle multiple exceptions using multiple catch blocks with a finally block. The try block contains the code which could potentially raise an exception. Then there are different catch blocks for each type of exception. The finally block contains code that is run no matter whether an exception is caught or not.