Tuesday, May 26, 2009

Exception Handling in .Net

A project task came up late last week to revamp and redesign an existing site, which was developed about a year back. The source was in C# and I had to quickly do a code walkthrough and prepare an effort estimate.

While reviewing the code, I noticed that almost every function, method and even tiny code snippets were wrapped around a try catch and the code within the catch section was either left empty or was simply throw ex;

I just wanted to write a quick note about exception handling based on what I have been doing over the last few years:

1. Catch an exception only when:
a. You are really intending to handle it and handle it appropriately
b. You want to find if it was some specific exception

2. There is no point in writing a try catch throw,
i.e. Writing the code given below is equivalent to writing nothing at all:
try
{
//Your code here
}
catch (Exception ex)
{
throw ex;
}

Instead you could just write your code and let the exception to bubble up.

3. Build a decent exception handler module that can contain options to log/publish the exceptions and helps to support the system.

4. A try catch in the UI would make more sense and it should appropriately redirect the user to a common errors page. Usually in the middle tier, the exceptions can be left to bubble up for the UI code to handle.

5. Create custom exception classes for specific purposes and throw them around your MT code. Using a try catch to find out if such a custom exception was thrown makes sense.

Example:
Write a UserNotFoundException that inherits from System.Exception.
You could throw this exception from a method that tries to fetch a user.
From another part of the code you can check specifically if this exception was thrown, and based on that you can route your code.

I am surely going to re-factor this website code and change it accordingly.
Post a Comment