Best exception for an invalid generic type argument

后端 未结 11 1195
孤城傲影
孤城傲影 2020-12-08 18:21

I\'m currently writing some code for UnconstrainedMelody which has generic methods to do with enums.

Now, I have a static class with a bunch of methods which are

11条回答
  •  温柔的废话
    2020-12-08 18:47

    I'm always wary of writing custom exceptions, purely on the grounds that they aren't always documented clearly and cause confusion if not named correctly.

    In this case I would throw an ArgumentException for the flags check failure. It's all down to preference really. Some coding standards I've seen go as far as to define which types of exceptions should be thrown in scenarios like this.

    If the user was trying to pass in something which wasn't an enum then I would throw an InvalidOperationException.

    Edit:

    The others raise an interesting point that this is not supported. My only concern with a NotSupportedException is that generally those are the exceptions that get thrown when "dark matter" has been introduced to the system, or to put it another way, "This method must go into the system on this interface, but we won't turn it on until version 2.4"

    I've also seen NotSupportedExceptions be thrown as a licensing exception "you're running the free version of this software, this function is not supported".

    Edit 2:

    Another possible one:

    System.ComponentModel.InvalidEnumArgumentException  
    

    The exception thrown when using invalid arguments that are enumerators.

提交回复
热议问题