With kudos to a good article at Java.net and to the book AntiPatterns: Refactoring Software, Architectures, and Projects in Crisis. We get a good eye-opener on the often-touted handle-your-exceptions-directive from your team lead or software architect. In the my previous posts, I have mentioned that anti-patterns should not be left unnoticed in the design and development time. I am starting this series of blog posts to collect and summarize an anti-pattern that I am sure, some stray developer out there in the world might be blissfully ignoring. So here goes the first: about exception handling. For more details, kindly refer to the java.net article or to the book.

Exception Handling Anti-patterns:

  • Log and Throw – don’t log then throw. Do only one thing.
  • Throwing Exception – a good programmer knows this is a _big_ no-no
  • Throwing the Kitchen Sink - if not throwing Exception is good, you might as well don’t throw a big gamut of checked exceptions
  • Catching Exception – again, while throwing Exception is a minus point, catching Exception is as evil as it is
  • Destructive Wrapping – you will lose your valuable stack trace with this… for example throw new NewException(oldException.getMessage()). Got it?
  • Log and Return Null – not always wrong, but it is more elegant to throw the checked exception instead of returning null
  • Catch and Ignore – well almost everyone is guilty of this… suppression of exceptions!
  • Throw from Within Finally – leave the finally alone. Be sure that your finally{} block will execute as peacefully and completely as it can
  • Multi-Line Log Messages – this will eat up a lot of your log resource
  • Unsupported Operation Returning Null – if you don’t have an implementation (yet), throw an unchecked UnsupportedOperationException instead of forcing the caller program to handle null
  • Ignoring InterruptedException – for you thread maniacs, try to do something when you catch this exception. The InterruptedException is a clue that your thread should stop doing whatever it is doing. For more of this, go study thread programming.
  • Relying on getCause() – and why rely? Rely on the actual thrown checked exception instead. Relying on the getCause() is a symptom of a bad design.

Tags: