It’s generally accepted practice that you should never catch Exception.

Of course, there are times when you need to try and ensure an exception never leaks your code, or when you are going to log details of the exception and then propagate the error in other ways. But, generally, there’s a consensus that catching Exception is a bad thing.

Except when there’s no other solution …

I’m writing a minor extension method to do type conversion from string values. Leveraging the built in TypeDescriptor gives a simple way to convert a string into almost anything else.

The core of the routine looks like this>

var converter = TypeDescriptor.GetConverter(typeof(T));
if (converter != null)
{
    return (T)converter.ConvertFromString(value);
}

Of course, what you’re seeing above is the prototype code, not production code.

While adding some basic error handling, I ran into some issues getting the exception handling right.

Digging into BaseNumberConverter with dotPeek, I found this lovely routine:

internal virtual Exception FromStringError(
    string failedText, Exception innerException)
{
    return new Exception(
        SR.GetString("ConvertInvalidPrimitive", 
            (object) failedText, (object) TargetType.Name), 
        innerException);
}

Yep, that’s right.

Instead of throwing a FormatException, InvalidCastException or something else civilized, it’s throwing a raw Exception.

So now my code needs to break with “good practice” and catch Exception in order to provide good error management.

Sigh.

Comments

blog comments powered by Disqus
Next Post
New WordTutor Release  24 Mar 2013
Prior Post
Code Analysis vs Code Contracts  16 Feb 2013
Related Posts
Avoid hardcoded wait times  26 May 2018
Guaranteed Progression  19 May 2018
Prefer declarative method names  03 Feb 2018
Using Premeditation  27 Jan 2018
With Relocation  20 Jan 2018
Using Consolidation  13 Jan 2018
Using Semantic Types  06 Jan 2018
Using Extension Methods  30 Dec 2017
Error Methods  25 Nov 2017
Pass implementations, not representations  14 Oct 2017
More smart-code posts »
Archives
February 2013
2013