Exceptions in .NET– part VII

Before going on, I need to confess one thing: I’m really frustrated! Why? simple: I was watching the damn build keynote and it stopped…right in the middle of the whole JS app for Windows 8…oh well, it’s probably a sign that it’s time to go back to my blog…

As you probably recall, in the previous post I’ve started presenting some guidelines for working with exceptions in C#. Today, I’ll keep doing that and I’ll introduce another guideline: it’s ok to catch an exception and re-throw it as “something” else if:

  • you handle only the exceptions you know how to
  • don’t forget to pass the old exception as the inner one in the new one.
Person GetPerson(Int32 id){
    try {
        //open SQL Server database
        //can throw SqlException
    }
    catch(SqlException ex) {
        //log the error
        //re-throw it as something else
        throw new InexistingPersonException(id, ex);
    }
}

Since we’re opening a database connection, we know we might end up with an SqlException whenever we open that database connection. Getting the information from a database is really an implementation detail and that’s probably someone who is consuming your code doesn’t need to know about.

Another interesting to notice is that I’ve passed the caught exception to the InexistingPersonException constructor. By doing this, I guarantee that the original exception isn’t lost and that may help me find the problem when someone calls back and complains about that exception.

Oh look, it’s saying that the day 1 keynote video will be available shortly! It’s probably best to wrap this post up right now Smile

And that’s it for now. Stay tuned for more.

Advertisements

~ by Luis Abreu on September 13, 2011.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: