Problem solve Get help with specific problems with your technologies, process and projects.

Better exception handling in .NET

Exception handling is the process by which a code base reacts to change. Here we link to two bloggers who have recently offered hints for exception handling in .NET.

Exception handling as defined by Wikipedia is the process by which a code base reacts to changes, or exceptions, in its normal flow. Code is exception-safe if run-time failures do not lead to invalid outputs, memory leaks or unreadable data.

Like chess, exception handling is an easy concept to understand but a difficult one to master. To that end two bloggers have recently taken up the topic, offering hints for better exception handling.

The more recent post is Scott Hanselman's Good Exception Management Rules of Thumb. Hanselman offers more than a dozen tidbits of advice, including:

  • "You shouldn't throw exceptions for things that happen all the time. Then they'd be 'ordinaries.'"
  • "Don't catch exceptions you can't do anything about. It's likely if you could do something about it, it wouldn't be exceptional…"
  • "There are reasons to swallow exceptions…but they are few and far between and they should be logged if appropriate and documented liberally."

Additional hints emerge in the comments for this blog entry.

David Barkol advises, "Catch exceptions at boundaries, for example [in] WCF (wrap exceptions in FaultException), [and in] WSE (wrap exceptions in SoapException)."

Meanwhile, Jason Kemp says, "For libraries mostly: Create a static, internal ExceptionHelper class and put all the logic for the default exceptions…in that class. It makes methods more readable, especially if there are three arguments to a method, all with restrictions. And you save lots of typing."

One comment points readers to a second blog entry on the topic -- Karl Seguin's Understanding and Using Exceptions.

Seguin and Hanselman touch upon many of the same points, namely the danger of exception swallowing and sprinkling too many Try/Catch statements throughout code.

Ultimately, Seguin decides the best way to handle exceptions is to use Try/Finally statements and to incorporate global exceptions into code. The latter, he says, "lets us write, in a centralized (i.e., easy to change) way, any exception logging we want and how to display the error in a friendly manner."

More on exception handling from

  • Webcast: Exception Handling and the CLR
  • Tip: Handling exceptions in Visual Studio.NET
  • Dig Deeper on .NET Framework 2.0 and Visual Studio 2005 development

    Start the conversation

    Send me notifications when other members comment.

    Please create a username to comment.