Best exception for an invalid generic type argument

C#GenericsException

C# Problem Overview


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 only meant to be used with "flags" enums. I can't add this as a constraint... so it's possible that they'll be called with other enum types too. In that case I'd like to throw an exception, but I'm not sure which one to throw.

Just to make this concrete, if I have something like this:

// Returns a value with all bits set by any values
public static T GetBitMask<T>() where T : struct, IEnumConstraint
{
    if (!IsFlags<T>()) // This method doesn't throw
    {
        throw new ???
    }
    // Normal work here
}

What's the best exception to throw? ArgumentException sounds logical, but it's a type argument rather than a normal argument, which could easily confuse things. Should I introduce my own TypeArgumentException class? Use InvalidOperationException? NotSupportedException? Anything else?

I'd rather not create my own exception for this unless it's clearly the right thing to do.

C# Solutions


Solution 1 - C#

NotSupportedException sounds like it plainly fits, but the documentation clearly states that it should be used for a different purpose. From the MSDN class remarks:

> There are methods that are not > supported in the base class, with the > expectation that these methods will be > implemented in the derived classes > instead. The derived class might > implement only a subset of the methods > from the base class, and throw > NotSupportedException for the > unsupported methods.

Of course, there's a way in which NotSupportedException is obviously good enough, especially given its common-sense meaning. Having said that, I'm not sure if it's just right.

Given the purpose of Unconstrained Melody ...

> There are various useful things that can be done with generic > methods/classes where there's a type constraint of "T : enum" or "T : > delegate" - but unfortunately, those are prohibited in C#. > > This utility library works around the prohibitions using ildasm/ilasm ...

... it seems like a new Exception might be in order despite the high burden of proof we justly have to meet before creating custom Exceptions. Something like InvalidTypeParameterException might be useful throughout the library (or maybe not - this is surely an edge case, right?).

Will clients need to be able to distinguish this from BCL Exceptions? When might a client accidentally call this using a vanilla enum? How would you answer the questions posed by the accepted answer to What factors should be taken into consideration when writing a custom exception class?

Solution 2 - C#

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

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

Solution 3 - C#

Generic programming should not throw at runtime for invalid type parameters. It should not compile, you should have a compile time enforcement. I don't know what IsFlag<T>() contains, but perhaps you can turn this into a compile time enforcement, like trying to create a type that is only possible to create with 'flags'. Perhaps a traits class can help.

Update

If you must throw, I'd vote for InvalidOperationException. The reasoning is that generic types have parameters and errors related to (method) parameters are centered around the ArgumentException hierarchy. However, the recommendation on ArgumentException states that

> if the failure does not involve the > arguments themselves, then > InvalidOperationException should be > used.

There is at least one leap of faith in there, that method parameters recommendations are also to be applied to generic parameters, but there isn't anything better in the SystemException hierachy imho.

Solution 4 - C#

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.

Solution 5 - C#

I'd go with NotSupportedException. While ArgumentException looks fine, it's really expected when an argument passed to a method is unacceptable. A type argument is a defining characteristic for the actual method you want to call, not a real "argument." InvalidOperationException should be thrown when the operation you're performing can be valid in some cases but for the particular situation, it's unacceptable.

NotSupportedException is thrown when an operation is inherently unsupported. For instance, when implementing an interface where a particular member doesn't make sense for a class. This looks like a similar situation.

Solution 6 - C#

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.

Solution 7 - C#

Id go with NotSupportedExpcetion.

Solution 8 - C#

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.

Solution 9 - C#

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.

Solution 10 - C#

I'd also vote for InvalidOperationException. I did an (incomplete) flowchart on http://www.truewill.net/myblog/index.php/2009/01/24/net_exception_throwing_guidelines">.NET exception throwing guidelines based on Framework Design Guidelines 2nd Ed. awhile back if anyone's interested.

Solution 11 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJon SkeetView Question on Stackoverflow
Solution 1 - C#Jeff SternalView Answer on Stackoverflow
Solution 2 - C#JaredParView Answer on Stackoverflow
Solution 3 - C#Remus RusanuView Answer on Stackoverflow
Solution 4 - C#RobbanView Answer on Stackoverflow
Solution 5 - C#mmxView Answer on Stackoverflow
Solution 6 - C#AliceView Answer on Stackoverflow
Solution 7 - C#Carl BergquistView Answer on Stackoverflow
Solution 8 - C#user117499View Answer on Stackoverflow
Solution 9 - C#PeterView Answer on Stackoverflow
Solution 10 - C#TrueWillView Answer on Stackoverflow
Solution 11 - C#BFreeView Answer on Stackoverflow