Skip to main content

When to Handle Exceptions

Tips and Tricks

I recently worked on a web app where the general philosophy on exception handling was: every method catches any exceptions that occur inside it. The reasoning? When an exception occurs, its effects get contained and the page continues to render. In practice, certain parts of a page would show up blank while other parts rendered normally.

Here's the problem with that approach. The user has no idea why things aren't working right. In this app, if authentication failed because the Active Directory server wasn't available, the login page just refreshed. No error messages. Nothing.

You should catch exceptions in your code only if you can answer yes to one or more of these:

  • Will I try to recover from the error in the catch block?

If you can't answer yes to any of those, don't handle the exception in that method. Let it propagate to the calling code where it might get handled more effectively.

One more thing, though. As a general rule in web apps, don't throw exceptions unless you absolutely have to. Throwing exceptions is expensive (CPU-wise) and can seriously hurt performance. If you expect an exception condition might occur in a routine, check for the condition and handle it without using throw.