Exceptions in .NET– part VI

As promised, today I’ll start presenting some interesting guidelines you should follow when working with exceptions. If there’s one guideline you should *always* follow, this is it: don’t catch every exception there is…especially if you’re developing libraries which will be used by other developers.

It’s important to realize that whenever you catch an exception, you’re saying that you’re expecting it and you know how to deal with it. In my experience, it’s far too common to see code like this (btw, I’ve used it before in previous posts, which was probably a bad idea…anyways, don’t do itSmile):

try {
    //some code
catch(Exception ex) {
    //just “eat it”

Whenever you write code like this, you’re saying that you know how to handle all the exceptions that might be thrown. Really? Are you sure about that? What do you expect to do whenever you get an OutOfMemoryException? Do you really know to handle it? And what about all the other exceptions which might be thrown? Things are even worse if you do something like this in a library which is going to be used by other developers. For starters, it’s difficult to know how the application which is consuming your library will respond to exceptions. Probably it can do more than you…probably, not…And that’s why it’s vital to let those exceptions your type can’t handle flow through the call stack. The worse thing that will happen is getting an unhandled exception which ends up killing the process. And this is not such a bad thing because 1.) most unhandled exceptions will probably be caught during development and 2.) sometimes ending the process is the best way to ensure that no data is corrupted.

Notice that the problem isn’t really catching any exception. It’s swallowing it! So, if you need to log all exceptions and you’re writing library code, then this is the correct way to do it:

try {
    //some code
catch(Exception ex) {
    //just log it

And now you’ll get your logging and you’re letting the exception flow through the call stack without changing its origin. And everybody is happy and you can go home an enjoy dinner in family…

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


~ 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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s

%d bloggers like this: