Catching Multiple Exceptions in single catch and Rethrowing Exceptions with Improved Type Checking – Java 7 Feature

In Java 7, catch block has been improved to handle multiple exceptions in a single catch block. If you are catching multiple exceptions and they have similar code, then using this feature will reduce code duplication. Let’s understand this with an example.

Before Java 7:

catch (IOException ex) {
     logger.error(ex);
     throw new MyException(ex.getMessage());
catch (SQLException ex) {
     logger.error(ex);
     throw new MyException(ex.getMessage());
}catch (Exception ex) {
     logger.error(ex);
     throw new MyException(ex.getMessage());
}

In Java 7, we can catch all these exceptions in a single catch block as:

catch(IOException | SQLException | Exception ex){
     logger.error(ex);
     throw new MyException(ex.getMessage());
}

If a catch block handles multiple exception, you can separate them using a pipe (|) and in this case exception parameter (ex) is final, so you can’t change it. The byte code generated by this feature is smaller and reduce code redundancy.

Another improvement is done in Compiler analysis of rethrown exceptions. This feature allows you to specify more specific exception types in the throws clause of a method declaration.

Let’s see this with a small example:

package com.journaldev.util;

public class Java7MultipleExceptions {

	public static void main(String[] args) {
		try{
			rethrow("abc");
		}catch(FirstException | SecondException | ThirdException e){
			//below assignment will throw compile time exception since e is final
			//e = new Exception();
			System.out.println(e.getMessage());
		}
	}

	static void rethrow(String s) throws FirstException, SecondException,
			ThirdException {
		try {
			if (s.equals("First"))
				throw new FirstException("First");
			else if (s.equals("Second"))
				throw new SecondException("Second");
			else
				throw new ThirdException("Third");
		} catch (Exception e) {
			//below assignment disables the improved rethrow exception type checking feature of Java 7
			// e=new ThirdException();
			throw e;
		}
	}

	static class FirstException extends Exception {

		public FirstException(String msg) {
			super(msg);
		}
	}

	static class SecondException extends Exception {

		public SecondException(String msg) {
			super(msg);
		}
	}

	static class ThirdException extends Exception {

		public ThirdException(String msg) {
			super(msg);
		}
	}

}

As you can see that in rethrow method, catch block is catching Exception but it’s not part of throws clause. Java 7 compiler analyze the complete try block to check what types of exceptions are thrown and then rethrown from the catch block.

Note that this analysis is disabled if you change the catch block argument.

Further Readin: Java Exception Handling Tutorial

About Pankaj

If you have come this far, it means that you liked what you are reading. Why not reach little more and connect with me directly on Google Plus, Facebook or Twitter. I would love to hear your thoughts and opinions on my articles directly.

Recently I started creating video tutorials too, so do check out my videos on Youtube.

I read a lot of books, below is the one I am currently reading.

Apart from that below are some of the recently read whitepapers. They are absolutely free to download.

Some of the video tutorials on Udemy I would recommend are;

NOTE: All the above video tutorial series are on huge discount now for $10 only, use Promo Code SUMMER1001

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Subscribe to JournalDev Newsletter
Get the FREE access to JournalDev Newsletter and Free PDF eBooks
*No Spam Guaranteed. By entering your email address, you agree also subscribing to our newsletter.
Oops! - Something went wrong.
Close
HTML5 Security Cheat Sheet PDF eBook FREE Download Now
Video Tutorial Series at 95% Discount, use Coupon Code 'SCOREASKILL' Enroll Now