Sunday, July 31, 2011

Java 7: Precise Rethrow

Previously, rethrowing an exception was treated as throwing the type of the catch parameter. For example, let's say that your try block could throw a ParseException or an IOException. To intercept all exceptions and rethrow them, you would have to catch Exception and declare your method as throwing an Exception. This is "imprecise rethrow", because you are throwing a general Exception type (instead of specific ones) and statements calling your method need to catch this general Exception.

This is illustrated below:

//imprecise rethrow.
//must use "throws Exception"
public static void imprecise() throws Exception{
	try {
		new SimpleDateFormat("yyyyMMdd").parse("foo");
		new FileReader("file.txt").read();
	} catch (Exception e) {
		System.out.println("Caught exception: " + e.getMessage());
		throw e;
	}
}
However, in Java 7, you can be more precise about the exception types being rethrown from a method. If you rethrow an exception from a catch block, you are actually throwing an exception type which:
  • the try block can throw,
  • no previous catch clause handles, and
  • is a subtype of one of the types in the declaration of the catch parameter
This leads to improved checking for rethrown exceptions. You can be more precise about the exceptions being thrown from the method and you can handle them a lot better at the calling site.
//java 7: precise rethrow.
//no longer "throws Exception"
public static void precise() throws ParseException, IOException{
	try {
		new SimpleDateFormat("yyyyMMdd").parse("foo");
		new FileReader("file.txt").read();
	} catch (Exception e) {
		System.out.println("Caught exception: " + e.getMessage());
		throw e;
	}
}

//this example handles ParseException
public static void precise2() throws IOException{
	try {
		new SimpleDateFormat("yyyyMMdd").parse("foo");
		new FileReader("file.txt").read();
	} catch(ParseException e){
	    System.out.println("Parse Exception");
	}catch (Exception e) {
		System.out.println("Caught exception: " + e.getMessage());
		throw e;
	}
}
(Note: Early documentation of this feature, states that you have to use a final modifier on the catch parameter, but this restriction was lifted later on, so is not necessary.)

Further Reading
Rethrowing Exceptions with More Inclusive Type Checking

2 comments:

  1. Hi Fahd,

    Great explanation! I'd like to borrow it (attributing it to you of course) for our University session in OSCON this week. Let me know!

    Cheers,
    Martijn

    ReplyDelete
  2. Hi Martijn,

    I'm glad you found this post useful. Feel free to use it in your session!

    ReplyDelete

Note: Only a member of this blog may post a comment.