Best exception for an invalid generic type argument

后端 未结 11 1141
孤城傲影
孤城傲影 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:26

    Throwing a custom made exception should always be done in any case where it is questionable. A custom exception will always work, regardless of the API users needs. The developer could catch either exception type if he does not care, but if the developer needs special handling he will be SOL.

    0 讨论(0)
  • 2020-12-08 18:33

    Apparently, Microsoft uses ArgumentException for that, as demonstrated on example of Expression.Lambda<>, Enum.TryParse<> or Marshal.GetDelegateForFunctionPointer<> in Exceptions section. I couldn't find any example indicating otherwise, either (despite searching local reference source for TDelegate and TEnum).

    So, I think it's safe to assume that at least in Microsoft code it's a common practice to use ArgumentException for invalid generic type arguments aside from basic variable ones. Given that the exception description in docs doesn't discriminate between those, it's not too much of a stretch, either.

    Hopefully it decides the question things once and for all.

    0 讨论(0)
  • 2020-12-08 18:33

    Id go with NotSupportedExpcetion.

    0 讨论(0)
  • 2020-12-08 18:34

    I would avoid NotSupportedException. This exception is used in the framework where a method is not implemented and there is a property indicating that this type of operation is not supported. It doesn't fit here

    • Shameless self Reference: http://blogs.msdn.com/jaredpar/archive/2008/12/12/notimplementedexception-vs-notsupportedexception.aspx

    I think InvalidOperationException is the most appropriate exception you could throw here.

    0 讨论(0)
  • 2020-12-08 18:36

    I would use NotSupportedException as that is what you are saying. Other enums than the specific ones are not supported. This would of course be stated more clearly in the exception message.

    0 讨论(0)
  • 2020-12-08 18:39

    How about inheriting from NotSupportedException. While I agree with @Mehrdad that it makes the most sense, I hear your point that it doesn't seem to fit perfectly. So inherit from NotSupportedException, and that way people coding against your API can still catch a NotSupportedException.

    0 讨论(0)
提交回复
热议问题