Menu
Topics Index
...
`


Exceptions >
Siva Nookala - 18 Mar 2016
Java supports multiple catch blocks for a single try block in order to handle different exceptions differently. The programs we have seen in Try Catch Block In Java can be enhanced to handle different exceptions differently.

If we assume that the method useTheResource might throw an ArithmeticException and ArrayIndexOutOfBoundsException, where as useItInAnotherWay might throw a NullPointerException, and we want different handling for different types of exceptions, then we can use multiple catch blocks as shown below.
ValuableResource vr = new ValuableResource();
try
{
    vr.initialize();
    vr.useTheResource();
    vr.useItInAnotherWay();
    vr.close();
}
catch(ArithmeticException ae)
{
     // Send a mail message here to the Arithmetic's Support group
    System.out.println("Our apologies. We have some problems with calculations, our arithmetic support team is looking into it.");
    vr.close();
}
catch(ArrayIndexOutOfBoundsException aioobe)
{
     // Log the stack trace for developers and send a pager message to the data maintenance group
    System.out.println("Our apologies. We have some problems with accessing the data, please call support for further details.");
    vr.close();
}
catch(NullPointerException npe)
{
     // Log the stack trace for developers
    System.out.println("Our apologies. We have some internal errors.");
    vr.close();
}
catch(Exception e)
{
     // Log the stack trace for developers, mail to arithmetic support group and send a pager message to the data maintenance group.
    System.out.println("Our apologies. Unknown error occurred. We will get back to you shortly.");
    vr.close();
}
Please note that the order in which the exceptions are caught is important. The most specific exception should be caught first. In other words the sub-class exception should be caught first and then the super-class exception should be caught. The classes NullPointerException, ArithmeticException and ArrayIndexOutOfBoundsException extends from the super-class Exception, so first they should be caught and finally the super-class Exception should be caught. Otherwise it causes a compilation error, if the order of the exceptions is not proper.

If we closely observe the program, we realize that the closing/cleaning of the resource is done at multiple times. Once in the try-block and once in every catch-block. There are good chances that we might forget calling it on of the catch blocks. Java supports the finally keyword to take care of situations like this. How we can avoid this duplicate code is explained in Java Finally Block In Exception Handling.

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.