0

I've encountered this a few times, and it seems very wrong to me that .NET operations should throw a System.Exception instead of something more specific. Is there a reason why one shouldn't rethrow this specific instance as InvalidCastException? Isn't it more appropriate to lump this case with InvalidCastException handlers?

For context, the method is this:

<System.Runtime.CompilerServices.Extension()> _
Public Function Parse(Of T)(ByVal str As String) As T
    Dim tc As TypeConverter = TypeDescriptor.GetConverter(GetType(T))
    If tc IsNot Nothing Then
        Dim prs As T = tc.ConvertFromString(str)

        Return prs
    Else
        Throw New InvalidCastException("Cannot convert from " & GetType(T).Name & " to String.")
    End If
End Function

and I'm considering wrapping Dim prs[...]Return prs with the System.Exception catch above.

The culprit is the System.Exception " is not a valid value" exception when the String is simply ""

What exception "should" it be? Or is System.Exception really a good exception for this case?

EDIT: On further thought, is System.Exception simply a result of the method being called the way it was? Int32.Parse Method (String) shows FormatException being the exception thrown by that function--would that be the best Exception to consider this case as?

j.i.h.
  • 815
  • 8
  • 29
  • You could do a `String.IsNullOrEmpty(str)` before trying to do the conversion. – Chris Stauffer Apr 03 '13 at 17:06
  • Well, the problem with that is that might eliminate conversions from types where an empty string is a value. I'm more wondering what the proper exception to throw is for "is not a valid value" exceptions--anything but System.Exception, right? – j.i.h. Apr 03 '13 at 17:12
  • 1
    I knew I was interpreting your question incorrectly :) I think [System.ArgumentException](http://msdn.microsoft.com/en-us/library/system.argumentexception.aspx) would cover your situation – Chris Stauffer Apr 03 '13 at 17:18

0 Answers0