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
might throw an
, where as
might throw a
, and we want different handling for different types of exceptions, then we can use multiple catch blocks as shown below.
ValuableResource vr = new ValuableResource();
// 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.");
// 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.");
// Log the stack trace for developers
System.out.println("Our apologies. We have some internal errors.");
// 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.");
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
from the super-class
, so first they should be caught and finally the super-class
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
keyword to take care of situations like this. How we can avoid this duplicate code is explained in Java Finally Block In Exception Handling