Monday, 27 June 2011

More precise exception rethrow

The more precise rethrow is a tricky one to understand. See if you can spot what the new feature is in the example below. Will it compile on pre-java-7? If not how would it need to be changed to compile on pre-java-7? The answers lie after the example.


public class MorePreciseExceptionRethrow {

static class Exception1 extends Exception {}
static class Exception2 extends Exception {}

public static void main(String[] args) throws Exception1, Exception2 {
try {
boolean test = true;
if (test) {
throw new Exception1();
} else {
throw new Exception2();
}
} catch (Exception e) {
throw e;
}
}

}


On Java 6 compiling the above gives the following exception.
Foo.java:18: unreported exception java.lang.Exception; must be caught or declared to be thrown
throw e;
^
1 error

This can be fixed for Java 6 by changing:
public static void main(String[] args) throws Exception1, Exception2 {

to:

public static void main(String[] args) throws Exception {{

So now you see the improvement that Java 7 offers with this feature. You can be more precise in the declaration of the exceptions that you rethrow. Very nice indeed.

No comments:

Post a Comment