Java

Catching Multiple Exception types (Multi-catch) – Java 7 +

In Java 7 a new feature is introduced to catch multiple Exceptions in a single catch block by defining a union of Exceptions to be caught in the catch clause. It allows a single catch block to handle more than one type of exception. This is also known as multi-catch.

Consider the following example written in a Java version prior to Java 7

try {
     // execute code that may throw SQLException, IOException and any other exception
} catch(SQLException e) {
     logger.warn("Exception thrown: " + e);
} catch(IOException e) {
     logger.warn("Exception thrown: " + e);
} catch(Exception e) {
     logger.error("Exception thrown: " + e);
}

Two catch blocks handles SQLException and IOException in the exact same way, but still you have to write two blocks of code, essentially creating duplicate codes.

This can be avoided in Java 7 and later versions by using multi-catch syntax:

try {
     // execute code that may throw SQLException, IOException and any other exception
} catch(SQLException | IOException e) {
     logger.warn("Exception thrown: " + e);
} catch(Exception e) {
     logger.error("Exception thrown: " + e);
}

Note that each Exception type the catch block can handle are separated by a vertical bar / pipe (|) character.

Advantages:

  • Exceptions of different types can be handled with single block of code
  • Eliminates duplicate codes

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.