Should you catch System.Exception?

Thursday, Dec 18, 2008 2 minute read Tags: generic .net
Hey, thanks for the interest in this post, but just letting you know that it is over 3 years old, so the content in here may not be accurate.

System.Exception is a funny class, it's a class that on its own isn't really that practical. In the talk that Brian Abrams talk on Framework Design Guidelines from PDC 2008 (a really interesting video) he mentions that if they could do it over again they would make System.Exception an abstract class.

And I completely agree. I hate nothing more than seeing code like this:

throw new Exception("Something bad happened!");

This line of code does not provide any insight into what has happened to produce the exception (ok, sure it's out of context, but I'm sure you've seen that used in context somewhere). It really comes about from a lack of understanding of the different exception types, and when they are appropriately used.

This then leads into the question I posed with this post, should you actually catch System.Exception?
I'm of the belief that you shouldn't catch this exception. All too often in exception handling I see code like the following:

try{
// do something
} catch (Exception ex) {
// do some exception handling
}

This exception handling isn't really that useful, from here all I have done is catch anything that's gone wrong, I have no opportunity to do anything unique with the different exception types nor could I appropriately handle an exception being thrown.

Take email sending, web apps frequently have email sending in them and obviously you'll need have some kind of error handling. The most likely exception to be thrown is the SmtpException so when catching that you want to inform the user that there was a problem sending their email. But there are other possible exceptions like null if you didn't set all the data appropriately. But that you may want a different message to the users. If all you're catching is Exception then how do you provide a different message?

But should that mean that you don't catch System.Exception? I say yes, you don't catch it, if you're appropriately catching known possible exceptions you shouldn't need System.Exception, that should be handled by the application-wide exception handling (within the Global.asax).

Appropriate exception handling means actually understanding just what could go wrong and handling those senarios, not just catching everything and not really understanding what could go wrong.

Moral of the story, the more you understand about what could go wrong within the application with make your life easier in the long run.