Multiple Catch In Java
As earlier we have checked Basics of Exception Handling in our previous article. Now its the example for Multiple Catch Clause to Manage various types of errors.
class MultiCatch{
public static void main(String []a){
int x,y,z=0;
try{
x=Integer.parseInt(a[0]);
y=Integer.parseInt(a[1]);
z=x/y;
System.out.println("Ans :"+ z);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Must Provide Two Values");
}
catch(ArithmeticException e) {
System.out.println("Second Value can not be Zero");
}
catch(Exception e) {
e.printStackTrace();
}
System.out.println("Will Always Execute");
}
}
In above example each type of error like ArrayIndexOutOfBounds and ArithmeticException are manage with separate catch clauses. Even if another type of error occurs like you provide values like 3 and x then last catch cluase for general Exception will be executed.