0

Try/Catch vs Global Exception-handling

by Jeremy 5. January 2010 17:51

Another developer recently asked me when try/catch blocks should be used in asp.net applications.  In most apps I write, I try not to pepper these statements throughout the code, but rather deal with exception handling on a global level.  The less code you write, the less code you have to maintain.  In my opinion, there are generally only two reasons to use try/catch statements: Either 1) you need to perform some action if the try code fails, or 2) you want to provide a more user-friendly (i.e. maintenance-developer friendly) error message.  Beyond these two cases, all unhandled exceptions can be dealt with on a global application level.  

For global exception handling, I prefer to use the open-source project ELMAH, which provides logging, notification, and UI functionality by simply plugging it in.  ELMAH performs this magic by using an http module to catch unhandled exceptions, combined with an http handler to display those logs via a UI.  However, if you don't want to use Elmah (stop being stubborn - it isn't that hard), you can always just put your exception handling code within the Application_Error method in the global.asax.

As for the two cases where try/catches should be used:
1) You need to execute some code if something fails.  Transactions are a good example - if you have a workflow that requires multiple steps to be completed within a transaction, and the first step fails, you will want to use a try/catch to perform a rollback within the finally block.

try
{
    //Start transaction
    //Perform step one
    //Perform step two
    //Commit transaction
}
catch(Exception)
{
    throw;
}
finally
{
    //Roll back the transaction
}

 

2) You want to provide an "English" error message.  Often-times, .net exception messages are fairly generic and don't always tip the developer off as to why something failed.  In these cases, you can catch the message and throw a new one that provides a more readable message.  Note that when you do this, you should always pass the caught exception to the constructor of your new exception - this way you won't lose the stack trace.


try
{
    //Get data from a vendor web service
}
catch(SqlException ex)
{
    string errorMessage = "The vendor api is not responding.  Give them hell.";
    throw new ServiceException(errorMessage, ex);
}

Currently rated 4.0 by 1 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

.NET | Software Maintainability | Exception Handling

Comments

Powered by BlogEngine.NET 1.4.5.0
Original Design by Laptop Geek, Adapted by onesoft