Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Attributes and Exceptions in .net

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;
    }
}
like image 626
Fionn Avatar asked Nov 24 '08 17:11

Fionn


Video Answer


1 Answers

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.

like image 142
Jon Skeet Avatar answered Oct 05 '22 21:10

Jon Skeet