Archive for December, 2011

New in Java 7 (03) – Multi catch

Saturday, December 3rd, 2011

I wanted to continue this post series but time goes by sooooo quickly (and I’m in a quite lazy mood lately).

Anyway, back for a new feature that Java has brought us: multiple catch clauses. And honestly, even if it’s a little one compared to other features, I find it a great addition to the Java developer’s toolkit. We (should) always seek to improve our code and reduce maintenance costs through refactoring etc, but sometimes the language doesn’t help.

Handling exceptions has been one area where code repetition often comes up. You’ve probably all written stuff like this:

} catch (SomeException ex) {
     logger.error(ex);
     throw ex;
} catch (OtherException ex) {
     logger.error(ex);
     throw ex;
}

And you’ll be pleased to know that with Java 7, you can now refactor your code and do this instead:

} catch (SomeException  | SomeOtherException ex) {
     logger.error(ex);
     throw ex;
}

Yummy!