Do not catch general exception types
If you use FxCop, then you are probably also aware of this rule. Exceptions should only be catched if they can be handled. A lot of exception handling code I’ve seen, are handling exceptions that could easily be avoided by simple If-statements. That’s why I don’t do a lot of try/catch blocks, other than when I’m working with external resources like files and MSMQ. In these situations, you cannot be sure of the outcome because you are not in control over the windows file system.
Here is what NOT to do:
try
{
//Do something with an XML file
}
catch (Exception)
{
Console.WriteLine("An error occured");
}
or
try
{
//Do something with an XML file
}
catch
{
Console.WriteLine("An error occured");
}
And here is an example of doing it correctly:
try
{
// Do something with an XML file
}
catch (XmlException)
{
Console.WriteLine("The XML has been corrupted");
}
catch (UnauthorizedAccessException)
{
Console.WriteLine("You do not have permission to save the document. Make sure the file isn't write protected.");
}
I personally only do exception handling at the UI and never at the data logic or business logic. It’s my rule of thumb on exception handling, but I do break it on rare occasions. I have found it to be the best way to avoid exceptions, because you make your code more robust this way.
Comments
Comments are closed