Multiple catch block

Multiple catch block

  • Used when more than 1 type of exception may be raised by a single piece of code
  • When an exception is thrown, each catch statement is inspected in order  & the first one whose type matches that of the exception is executed
  • After 1 catch statement executes, the others are bypassed & execution continues after the try/catch block
  • An exception subclass must come before any of their super classes
Example
class test
{
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] = 9;
}
catch(ArithmeticException e)
{
System.out.println(“Divide by 0: ” + e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“Array index oob: “+e);
}
System.out.println(“After try/catch blocks.”);
}
}

Output:
a = 4
Array index oob: java.lang.ArrayIndexOutOfBoundsException: 42
After try/catch blocks.

Leave a Reply

Your email address will not be published. Required fields are marked *