More on Java 7 – Try/Multi-catch!

Rambling on a bit more from my previous post about new Java 7 syntax, I wanted to comment a bit on how happy I am with the spiffy new “multi-catch”!

One thing I REALLY hate to see in code is ugly try catch blocks. What do I mean by ugly? Let me give you an example

try{
     openUserInputStream(DEFAULT_FILENAME);
     parseUserInput();
     closeUserInputStream(DEFAULT_FILENAME);
}catch(GnarlyParseException e0){
     logGnarlyException(e0);
}catch(GnarlySyntaxException e1){
     logGnarlyException(e1);
}catch(IOGnarlyOpenException e2){
     logIOException(e2);
}catch(IOGnarlyCloseException e3){
     logIOException(e3);
}

I’ve seen a lot of code that looks very similar and in my honest opinion, it’s a bit of an eyesore. We have 4 unique catch blocks performing 2 unique actions. Now, since it would appear (from my very contrived example) that we’re doing nothing more that logging here, there are several ways around this. In fact, I’d argue that there are several ways to re-factor this and make it a little more “pretty”. But that, my friend, is a different post for a different day (probably a day in the very near future – I’ve been reading “Uncle Bob” Martin’s Clean Code and have quite a bit to say…)

What I’m here to write about now is the spiffy new multi-catch in Java 7.

Multi-catch allows you to place more than one exception within one catch block, separating each with the “|” character!

So, I can take the above code and modify the try/catch to look like this:

try{
     openUserInputStream(DEFAULT_FILENAME);
     parseUserInput();
     closeUserInputStream(DEFAULT_FILENAME);
}catch(GnarlyParseException|GnarlySyntaxException e0){
     logGnarlyException(e0);
}
catch(IOGnarlyOpenException|IOGnarlyCloseException e1){
     logIOException(e1);
}

Just a little FYI – the Exceptions are “caught” from left to right in a block like this, just like they’re caught top down. That is, lets suppose that IOGnarly* Exception both extend IOException.

Lets also spoz that we’d like to handle a general IOException as well. If we were handling each with it’s own catch block it’d be a syntax no-no to put IOException in a block above the other two. You’re compiler would yell, kick, and scream, tell you to fix your code and send an email to your boss and all of your co-workers.

It gets just as angry if you try to do something like this ” catch(IOException|IOGnarlyOpenException e)”so don’t do that ! Good stuff to remember if you plan on taking an OCJP 7 exam 😉

Leave a comment

Filed under Java

Leave a comment