blog

Home / DeveloperSection / Blogs / Exception Handling in Java: Combining Exception Handlers

Exception Handling in Java: Combining Exception Handlers

Ailsa Singh1764 20-May-2016

In my previous post, we have learnt how we can handle multiple exceptions in our code by providing multiple numbers of catch block specific to a particular exception. But Java SE 7 introduces a very handy feature by which we can combine several exceptions in a single catch block. Let’s learn this new feature.

Look at the following code segment that contains multiple exception handlers:

try {
// Say some file parser code here...
} catch (IOException ex) {
// log and rethrow exception
} catch (ParseException ex) {
// log and rethrow exception
} catch (ClassNotFoundException ex) {
// log and rethrow exception
}

 

The code parses the contents of a given file. The process may generate different types of exceptions, such as IOException, ParseException, and ClassNotFoundException. Each exception handler for these errors logs the exception and re-throws another exception to the caller. We discuss this re-throwing business in later posts. What is important here is that all exception handlers execute the same piece of code. So why not combine them? Java SE 7 facilitates this.

Here’s what the new code looks like:
try {
// Say some file parser code here...
     } catch (IOException ex | ParseException ex |
              ClassNotFoundException ex) {
                     // log and rethrow exception
   }

 

Here, all those exception handlers that have common code are combined by using a logical OR operator between their exception types. This makes the code simpler. However, this feature works only on Java SE 7 and above. If we want to take different actions for different exceptions, we do not have a choice other than to provide individual exception handlers, as stated earlier.

How Runtime Matches catch Blocks

Whenever an exception occurs in running code, the search for the first matching catch block begins and the rules listed here are followed:

•A thrown exception object is caught by the catch block that specifies the class of the occurred exception or its superclass.

•In the case of multiple catch blocks, these are evaluated sequentially in the order they are specified by applying the first rule. If a catch block is found, the rest of the catch blocks are ignored.

•A certain catch block will never be executed if a catch block containing its superclass is listed prior to it. In such situations, a compile-time error is generated.

•The compiler forces the programmer to handle all checked exceptions. In other words, we must provide error handling for all exceptions except for the RuntimeException and its subclasses.

•If the try block never throws an exception specified in the catch list, the compiler generates an error.


Updated 15-Mar-2018

Leave Comment

Comments

Liked By