Effective Exception Handling :: Doing It Right

I've gone over why catching exceptions is a bad thing in many case, but surely there is a reason for having catch blocks? Absolutely. They just need to be used carefully. In fact, writing them should be seen as taking on a rather critical responsibility. Every time a catch block is deployed you are saying "Hey guys, I've got this one under control - leave it up to me". When you don't use them effectively, you've dropped the ball in a big way.

To figure out if and when to use them, let me present three simple rules:

  1. Understand what will happen if you don't catch exceptions. This is kind of hypothetical in Java, as we are forced to explicitly declare exceptions that we want to propagate. C# does away with checked exceptions, which as actually a good thing. I'll explain this a bit more later.
  2. Evaluate whether you can present a better experience to the user by catching the exception and diverting program flow. Can we recover from the error? Is the situation so far out of control that we can't do anything? Does it help to display a specific output when the error occurs?
  3. Implement your own exception handlers only if the above is true. I find that this is more often than not performed somewhere very close the user interface layer, and very rarely in the business logic. I'll cover some scenarios further down that illustrate when exceptions should be caught.

I've been giving a lot of thought as to how to illustrate doing it right. The conclusion I came to is that there are no hard and fast rules, as there are such a wide variety of scenarios in which errors occur. From there it seemed appropriate to formulate some real world examples. Not just mere code snippets, but reasonably complete sections of code that cover the three rules above.

What I want to achieve is a fairly comprehensive sample of environments that will be added to as they are completed, and extended to cover additional areas if requested. Over the next few weeks you can expect to see examples of Java code in the following contexts:

I'm sticking to Java at the moment as that's the area I'm most experienced in. However, I'm open to covering other languages and frameworks such as: