Introduction
The code bound by the try block need not always throw a single exception. If in a try block multiple and varied exceptions are thrown, then you can place multiple catch blocks for the same try block in order to handle all those exceptions. When an exception is thrown it traverses through the catch blocks one by one until a matching catch block is found. The program structure in such a case is:
Code: Java
try
{
// statements with multiple and varied exceptions
}
catch (<exception_one> obj)
{
// statements to handle the exception
}
catch (<exception_two> obj)
{
// statements to handle the exception
}
catch (<exception_three> obj)
{
// statements to handle the exception
}
Code: Java
class Multi_Catch
{
public static void main (String args [ ])
{
int square_Array [ ] = new int [5];
try
{
for (int ctr = 1; ctr <=5; ctr++)
{
square_Array [ctr] = ctr * ctr;
}
for (int ctr = 0; ctr <5; ctr++)
{
square_Array [ctr] = ctr / ctr;
}
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println ("Assigning the array beyond the upper bound");
}
catch (ArithmeticException e)
{
System.out.println ("Zero divide error");
}
}
}
Code:
Assigning the array beyond the upper bound
Code: Java
class Multi_Catch
{
public static void main (String args [])
{
int square_Array[] = new int[5];
try
{
for (int ctr = 0; ctr <5; ctr++)
{
//do nothing
}
for (int ctr = 0; ctr <5; ctr++)
{
square_Array[ctr] = ctr / ctr;
}
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println ("Assigning the array beyond the upper bound");
}
catch (ArithmeticException e)
{
System.out.println ("Zero divide error");
}
}
}
Code:
Zero divide error
There is also a generic exception class called the Exception class. This class is capable of catching any type of exception. So while catching the exception, if you do not want to specify the exception type, you can put the generic exception and still handle any kind of exception the exception coming up. Take a look at example given below, though the exception generated is the ArithmeticException, the Exception class is able to handle it. This takes the form as:
Code: Java
class GenericException
{
public static void main (String args[])
{
try
{
int num = 34, den = 0;
int quot = num / den;
}
catch (Exception e)
{
System.out.println ("Error in the code");
}
}
}
Code: Java
class Multi_Catch
{
public static void main (String args [])
{
try
{
Object Arr_Obj [ ] = new String [2];
Arr_Obj [0] = new Integer (15);
}
catch (ArrayStoreException e)
{
System.out.println ("Incompatible object Types");
}
catch (Exception e)
{
System.out.println ("Generic Exception");
}
}
}