Is there a standard .NET exception to throw when a class doesn't implement a required attribute?
Suppose I want to throw a new exception when invoking a generic method with a type that doesn't have a required attribute. Is there a .NET exception that's appropriate for this situation, or, more likely, one that would be a suitable ancestor for a custom exception?
For example:
public static class ClassA
{
public static T Do开发者_高级运维Something<T>(string p)
{
Type returnType = typeof(T);
object[] typeAttributes = returnType.GetCustomAttributes(typeof(SerializableAttribute), true);
if ((typeAttributes == null) || (typeAttributes.Length == 0))
{
// Is there an exception type in the framework that I should use/inherit from here?
throw new Exception("This class doesn't support blah blah blah");
// Maybe ArgumentException? That doesn't seem to fit right.
}
}
}
Thanks.
the way I see it, you can go one of 3 ways...
1) NotSupportedException
2) NotImplementedException
3) You can make your own Exception type
I know I've seen some of the built-in code templates throw a NotImplemented exception as a placeholder, so that might be a good place to start.
NotSupportedException is a good choice I believe. Also TargetException and TargetInvocationException are specific for Reflection.
NotSupportedException as NotImplemented is technically for stubs which is not what is happening here. The type isn't supported.
That being said I don't know why MS has failed to provide canonical list with their internal definitions. It boggles the mind.
精彩评论