20080108

Why Multiple Exceptions is so hot

It seems that Monday was Exceptional arguments day - Catching multiple exceptions: good or bad?

I have to admit that I could not be bothered to follow all the replies, after the 10th stock answer and the 10th wannabe architect half baked wisdom, I stopped reading.

The reason why there are so many right and even more wrong answers is that Exception handling is contextual, and in the end the best you can ever do is achieve a 'reasonable compromise'. Exceptions represent unforeseen circumstances, or at least that was the original idea [I don't want to judge programming style, what matters is accurate 1s and 0s and the maintainability of the code that produces them], and so someone needs to sit and think about the bigger picture.

I have seen some strange programming environments over the years, as far as Exceptions go they range from:

catch (Throwable ignoreall) {}

to dropping into a full blown AI fault analysis and blame system. Both techniques were correct for their context, and have served their masters well. This is one of the reasons why writing re-usable software is so hard; you cannot predict the context of its eventual use.

My advice is to avoid writing lines of code like the above, only special circumstances demand that degree of insanity. Generally you should follow these basic guidelines:

  • Never lose an Exception, always do something with it, even if that is just passing it to a piece of null code (AOP later)
  • Play Ball [sometimes I pander to the audience], catch and throw anew, that way you can always participate if need be.
  • Dots in handlers are dangerous, there is nothing worse than a NPE masking the real issue.
  • Never throw other people's Exceptions, it can make a real mess of your dependency tree. Catch then wrap or fix.
  • Don't throw when you can return, thrown business related objects make an architectural mess.
As far as the original article goes, any syntax that promotes good practice is beneficial, and this suggestion is one that might encourage developers to avoid unhealthy temptation. Java is a general language and so I don't really care how many different ways there are to specify what you want to do as long as the Jit compiler still has the opportunity to do a good job.

Blogged with Flock

No comments: