Exceptions, part 3

This is part three in a series about using exceptions in both Java and .NET. You can find part one here, and part two here.

When to catch exceptions

In part two of this series, we covered the right conditions for throwing exceptions. In this article, I would like to cover the other end of the spectrum: catching exceptions.

It turns out there is just one simple rules to catching exceptions:

  • Never, ever, ever-ever catch the base exception class.

Like many of my rules, the rationale behind this rule comes from experience. And like most bad experiences, it was caused by other people’s code ;-).

A few years ago, I was debugging a piece of Java code of a colleague that did not work right. The code was supposed to generate a file somewhere on the filesystem, but it did not do so. But no exception was thrown; everything seemed to work OK. As it turned out, he did the following somewhere deep in the code:

try {
  doSomething();
  doAnotherThing();
  andAnotherThing();
} catch (Exception e) { 
}

And that is just a bug waiting to rear it’s ugly head.

All this because, and I quote: All those methods are mine and should not have caused exceptions anyway. And besides, those throws declarations exceptions are driving me nuts. Right.

However, like all rules, it comes with an exception:

  • Except when wrapping it in another exception.

Wrapping an exception in another exception is possible in both .NET and Java (since JDK 1.4). You can add more information to the wrapper with a message, but you can also use a wrapper exception to limit the types of exceptions a methods throws.

Comments are closed.