while writing a custom attribute in C# i was wondering if there are any guidelines or best practices regarding exceptions in attributes. Should the attribute check the given parameters for validity? Or is this the task of the user of the property?
In a simple test I did the exception was not thrown until i used GetCustomAttributes on a type with an exception throwing attribute. I just think it's a bit awkward to get an exception from an Attribute only when explicitly asking for them.
Example Attribute with exception:
[AttributeUsage(AttributeTargets.Interface, AllowMultiple = false, Inherited = false)]
sealed public class MyAttribute : Attribute
{
public string SomeValue { get; private set; }
public MyAttribute(string someValue)
{
if(string.IsNullOrEmpty(someValue))
{
throw new ArgumentNullException("path");
}
if(!someOtherCheck(someValue))
{
throw MyAttributeException("An other error occured");
}
SomeValue = someValue;
}
}
Attributes are only actually constructed when you use reflection, so that's the only time you can throw an exception. I can't remember ever using an attribute and having it throw an exception though. Attributes usually provide data rather than real behaviour - I'd expect the code which uses the attribute to provide any validation. I know this isn't like normal encapsulation, but it's the way it tends to be in my experience.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With