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(
            (object) failedText, (object) TargetType.Name), 

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.



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
Browsers and WSL  31 Mar 2024
Factory methods and functions  05 Mar 2023
Using Constructors  27 Feb 2023
An Inconvenient API  18 Feb 2023
Method Archetypes  11 Sep 2022
A bash puzzle, solved  02 Jul 2022
A bash puzzle  25 Jun 2022
Improve your troubleshooting by aggregating errors  11 Jun 2022
Improve your troubleshooting by wrapping errors  28 May 2022
Keep your promises  14 May 2022
February 2013