Wednesday, 22 January 2014

MULTIPLE catch CLAUSES IN JAVA

HANDLING MULTIPLE catch CLAUSES
Java Exception Handling:catching multiple exceptions

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 general form is as shown below:

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


Example:
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");
        }
    }
}

Output:

Assigning the array beyond the upper bound



 


No comments:

Post a Comment