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(); 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.
|