Search code examples
.netvb.netexceptionargumentexception

Throw an InvalidCastException or ArgumentException in structure's conversion method


I have some structures that are created from parsed JSON templates. So I have created a FromValue() method which converts the JSON string value to a structure to ensure only valid values are used and magic strings are not needed when editing the JSON object.

If an invalid value is provided, should I be throwing an InvalidCastException - as I am "casting" a string value to my structure type - or, an ArgumentException - as the argument is indeed invalid?

Here is one of my structures as an example:

Public Structure stContentJustify
    Public Shared ReadOnly Property Left As stContentJustify
        Get
            Return New stContentJustify("left")
        End Get
    End Property

    Public Shared ReadOnly Property Center As stContentJustify
        Get
            Return New stContentJustify("center")
        End Get
    End Property
    Public Shared ReadOnly Property Right As stContentJustify
        Get
            Return New stContentJustify("right")
        End Get
    End Property
    Public Shared ReadOnly Property Spaced As stContentJustify
        Get
            Return New stContentJustify("spaced")
        End Get
    End Property

    Public Shared Function FromValue(ByVal vsValue As String) As stContentJustify
        Select Case vsValue
            Case "left"
                Return Left
            Case "right"
                Return Right
            Case "center"
                Return Center
            Case "spaced"
                Return Spaced
            Case Else
                Throw New InvalidCastException(vsValue & " cannot be cast to a valid ContentJustify value.")
                'Throw New ArgumentException(vsValue & " is not a valid ContentJustify value.")
        End Select
    End Function

    Public ReadOnly Property Value As String

    Private Sub New(ByVal vsValue As String)
        Value = vsValue
    End Sub

End Structure

Solution

  • You're not casting anything there. You never need to throw an InvalidCastException yourself. It will be thrown if you actually perform a cast that is invalid. In your case, the issue is that the argument passed to the method is not valid and that is the very definition of an ArgumentException.