Correct exception to throw for an unhandled switch case for an argument?

后端 未结 5 2360
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-19 22:26

NOTE: This is different than the proposed duplicates as this deals with an argument rather than a value. The behavior and applicable scenarios are essentially different.

相关标签:
5条回答
  • 2021-02-19 22:29

    InvalidArgumentException. when user pass some invalid value or null value when value value is required, it is recommended to handle InvalidArgumentException .

    0 讨论(0)
  • 2021-02-19 22:32

    I'd throw the InvalidEnumArgumentException as it will give more detailed information in this case, you are checking on an enum

    0 讨论(0)
  • 2021-02-19 22:35

    ArgumentException looks the most correct to me in this instance (though is not defined in the BCL).

    There is a specialized exception for enum arguments - InvalidEnumArgumentException:

    The exception thrown when using invalid arguments that are enumerators.

    An alternative is ArgumentOutOfRangeException:

    The exception that is thrown when the value of an argument is outside the allowable range of values as defined by the invoked method.

    The logic for using these is that the passed in argument (value) is not valid as far as someFunc is concerned.

    0 讨论(0)
  • 2021-02-19 22:43

    Since you have the login in a function you can throw InvalidArgumentException.

    The exception that is raised when a parameter that is not valid is passed to a method on the referenced connection to the server.

    EDIT: A better alternative would be: ArgumentException, since InvalidArgumentException in Microsoft.SqlServer.Management.Common namespace. Something like:

    throw new ArgumentException("Unhandled value: " + value.ToString());
    
    0 讨论(0)
  • 2021-02-19 22:48

    If you were using Code Contracts (something I HIGHLY recommend), you would put this at the start of the method:

    Contract.Requires(value == SomeEnum.One || value == SomeEnum.Two);
    

    If you want to check a range of an enum which has too many individual values to write them all explicitly, you can do it like this:

    Contract.Requires(SomeEnum.One <= value && value <= SomeEnum.Two);
    
    0 讨论(0)
提交回复
热议问题