Java 7: The Most Confusing Feature

Java 7 has this new feature – now you can add the keyword final to the catch clause. This feature is pretty confusing. I tried to find bits and pieces that would make me wanna write the final qualifier in front of the exception ‘s type. This blog didn ‘t help much.

I wrote a little program below that purposely divides by zero. This program works with or without the final keyword, and the output is the same. I ‘d appreciate if someone would give me a clear code example (just the code, please) that would show why this confusing feature has been added to the language.

public class TestStackTraceJava7 {

TestStackTraceJava7() {

try{

divideByZero();

} catch (ArithmeticException e){

System.out.println( “Don ‘t divide by zero! “);

}

}

// This won ‘t compile: int divideByZero() throws Exception {

int divideByZero() throws ArithmeticException {

try{

int i=25/0;

} catch (final ArithmeticException e){

System.out.println( “Caught ArithmeticException and rethrowing… “);

throw e;

}

return -1;

}

public static void main(String[]args){

new TestStackTraceJava7();

}

}

Update. I ‘d like to thank Aleksander Borisov, who responded to my post and created an example that illustrates the usage of the final exceptions.

But the question remains the same, “Why making the language more confusing than it has to be? ” Just look at this code snippet from the Alexander ‘s post:

private void throwExceptions() throws A, B, C {

try {

throwAccordingToIndex(new Random().nextInt(2));

} catch (final Exception e){

System.out.printf( “Caught %s and rethrowing…%n “, e);

throw e;

}

}

Basically this code reads, “Even though I ‘m catching only Exception, actually, it can be one of the three types of Throwable objects: A, B, or C. I need to rethrow it to the caller anyway, and by the time the caller will get it, the type Exception will change back to one of three: A, B, or C “. To make things even more confusing, writing the keyword final here is not mandatory.

Currently, I ‘m teaching a Java class for the beginners, and tomorrow session happens to be about Java exceptions. I ‘ll just briefly mention that Java 7 introduces a confusing and not overly useful feature called final rethrows. Take a note of it, but you can live happily without ever using this feature.

Actually, I know one use of it, and if I ‘m not going to fall asleep on the bus while going home from work, I ‘ll write an blog describing a quite unusual scenario when final exceptions may help you. Stay tuned…

Advertisement

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 )

Facebook photo

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

Connecting to %s