01 Sep 2010

These days, I've seen a lot of code like this in the code base I’m working on:

try
{
    //Do some parsing or any dangerous operation
}
catch (Exception)
{
    //Return something, as if nothing happened
}

Now, I can understand why this is done. It feels safe. After all, if you are in a method that is supposed to return something, you can simply return a default value if an exception shows up, right?

Wrong. Very wrong.

Please, only catch the exceptions you know you can recover from. Let’s say you parse something in the try block. At first, check if there is a TryParse method to do that instead, so no exception is thrown in the first place. If that’s not an option, only catch the exceptions that are caused by the parsing process, not all exceptions.

Leave the exception you can’t deal with bubble up the calling hierarchy. At the end, the will reach a process that can handle them or that will fail and log them. That is the way to go in all situations.

For excellent references on exceptions guidelines, please see  the excellent

Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries (2nd Edition).



blog comments powered by Disqus