Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Java (http://www.go4expert.com/articles/java-tutorials/)
-   -   Multiple 'catch' clauses in Java (http://www.go4expert.com/articles/multiple-catch-clauses-java-t4167/)

Sanskruti 6May2007 14:55

Multiple 'catch' clauses in Java
 

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
}

Let us consider an example in which we are using two catch clauses catching the exception ArrayIndexOutOfBoundsException and ArithmeticException. In the first example a deliberate attempt has been made to store the value in the array beyond itís upper limit thus causing the program to throw the exception ArrayIndexOutOfBoundsException, and to go to the first catch block. In the next example this error is rectified and the program is run again. A new error comes up which is the zero divide. Now this time the second catch block handles the error, and the first catch block is skipped.

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

The output of the program is:

Code:

Assigning the array beyond the upper bound
The following example is the modified version of the listing 5.7 in which the ArithmeticException is thrown and the control 1 goes to the second catch block.

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

The output of the program is:

Code:

Zero divide error
This way you can have a combination of many types of exceptions handling routines in your program.

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

The generic Exception class can also be used with multiple catch blocks. While using the Exception class with multiple catch blocks one must exercise caution so as to not to keep this class in the top most catch clause. Since Exception class is the superclass of all the exceptions, it tends to catch any kind of exception. Consequently, all other catch blocks below it will be unreachable and your code will not be able to compile. So if you want to catch various exceptions particularly along with the generic exception, the generic exception must be put in the last catch. Take a look at the following example:

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

In the above example, an array of Object class is created in which you are storing the reference of the String object. In the next statement, you are trying to reference the Arr_Obj to Integer type of object. This amounts to assigning an incompatible object type to the array element. An exception ArrayException is raised and caught (ArrayException is raised when an array element is assigned an incompatible object type). Note the position of the generic exception as the last catch block. If you had kept this block as the first catch block you program would not have complied at all though logically both the exception seem to be very appropriate.


All times are GMT +5.5. The time now is 22:11.