Multiple Catch In Java Example
Chapter:
Exception Handling
Last Updated:
08-06-2017 13:55:53 UTC
Program:
/* ............... START ............... */
public class MultipleCatchJava {
public static void main(String args[]) {
try {
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
} catch (ArithmeticException e) {
System.out.println("Divide by 0: " + e);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index : " + e);
}
System.out.println("After try/catch blocks.");
}
}
/* ............... END ............... */
Output
C:\>java MultipleCatches
a = 0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.
C:\>java MultipleCatches TestArg
a = 1
Array index : java.lang.ArrayIndexOutOfBoundsException:42
After try/catch blocks.
Notes:
-
If you have to perform different tasks at the occurrence of different Exceptions, use java multi catch block.
- A try block can be followed by multiple catch blocks.
- It is important to remember that exception sub classes inside catch must come before any of their super classes otherwise it will lead to compile time error.
Tags
Multiple Catch, Java, Exception Handling