Wednesday, August 30, 2006

Exceptions

Exceptions

When throwing/handling exceptions you should be aware of a few things:

Take a look at the following code:

try

{

db.ExecuteNonQuery(dbCommandWrapper);

log.Debug("Executed: " + sqlCommand);

}

catch (SqlException ex)

{

throw new ApplicationException("Exception encountered while inserting data", ex);

}

Notice a few things:

* I am catching a specific exception instead of catching the generic Exception. So instead of catching all exceptions, just catch the exceptions that you intend to handle.
* I am throwing a new exception of type ApplicationException, and I am wrapping the original exception into the InnerException property. This accomplishes two things: It gives the caller the ability to handle exceptions of type ApplicationException instead of handling Exception or SqlException typed exceptions. The case for this is that if the business tier calls the data tier and the data tier encounters a SqlException, then either the data tier should handle the SqlException and don't throw it, or create a new exception and wrap the SqlException and throw this new exception to the business tier. This eliminates the need for the business tier to try to handle SqlException exceptions when the Data tier should handle the SqlException. Another point to note is that you should probably stay away from using the following throw commands: throw; throw ex; and throw new ApplicationException("some message"); as all three will overwrite any stack trace for the exception up to the point when the throw was executed, so all past stack traces before the throw was executed will be lost.

Comments: Post a Comment



<< Home

This page is powered by Blogger. Isn't yours?