Java 7 Multi Catch Block

In the pre Java 7 world, you would handle exceptions by writing separate catch blocks for different types of exceptions that can occur in the try block. In case of related exception, the derived class exception are listed above the base class exception, e.g. FileNotFoundException should be listed above IOException since former is derived from the latter. Java 7 multi catch block provides you the flexibility to combine such catch blocks, provided you have similar code to handle these exceptions.

Lets have a look at the below example where we handle all the exceptions thrown by the try block in a single catch block, but still specifying the type of exceptions we are handling:

Around The World Flights - Promo Code WORLD15
package com.quicklyjava;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class Java7MultiCatch {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		try {
			BufferedReader br1 = new BufferedReader(new FileReader(
					"c:/test.txt"));
			String str = null;
			Class.forName("oracle.jdbc.driver.OracleDriver");

			Connection con = DriverManager
					.getConnection("jdbc:oracle:thin:@127.0.0.1:1565:myDB");
		} catch (IOException | ClassNotFoundException | SQLException e) {
			System.out.println("Multi catch block here!");
			e.printStackTrace();
		}

	}
}

Although this feature might save some coding effort on the part of the developer, but it makes sense to handle individual exceptions separately as each exception is different and it also improves code readability.

You can download the eclipse project of the code explained in this tutorial:
Java7MultiCatch.zip (3K)

One response to “Java 7 Multi Catch Block”

  1. Raja

    Greetings. I actually did some trap surfing and organize this blog. I decided sooner than way of this blog present up and it is in point of fact incredible.I clearly genuinely fancy your website.Perfectly, the chunk of posting is in oath the altogether finest on this genuinely quality though subject. I added it and i

Leave a Reply