What exception to throw from a property setter?

后端 未结 7 2101
醉话见心
醉话见心 2020-12-08 02:24

I have a string property that has a maximum length requirement because the data is linked to a database. What exception should I throw if the caller tries to set a string ex

相关标签:
7条回答
  • 2020-12-08 02:48

    Remember how many problems in computer science are solved by adding an extra level of indirection?

    One approach would be to create a new type, FixedLengthString, say. It would be instances of that type that validate lengths of strings they are initialised with - with a conversion operator to do type conversion from a plain string. If your property setter takes such a type as its argument then any violation would become a type conversion exception instead of an argument/ property exception.

    In practice I would rarely do this. It smells a bit of taking OO too far - but in some cases it can be a useful technique, so I mention it here for completeness.

    0 讨论(0)
  • 2020-12-08 02:50

    To me ArgumentException (or a child) makes more sense, because the argument (value) you provided is not valid, and this is what ArgumentException was created for.

    0 讨论(0)
  • 2020-12-08 02:55

    You may use InvalidOperationException. That's a compromise. I wouldn't bother using an ArgumentException either.

    0 讨论(0)
  • 2020-12-08 03:02
    public IPAddress Address
    {
        get
        {
            return address;
        }
        set
        {
            if(value == null)
            {
                throw new ArgumentNullException("value");
            }
            address = value;
        }
    }
    

    via MSDN

    0 讨论(0)
  • 2020-12-08 03:06

    Try to use existing exceptions whereever possible. In this case use InvalidOperationException because the incoming value is bringing the object in an inconsistent state. Custom exceptions can be created when a specific handling with the custom exception is needed. In this case you only throw an exception with some text, so use the InvalidOperationException.

    When throwing the InvalidOperationException show the value that has been passed to this setter.

    0 讨论(0)
  • 2020-12-08 03:08

    Have a look through mscorlib.dll with Reflector, in a similar situation such as System.String.StringBuilder.Capacity Microsoft use ArgumentOutOfRangeException() similar to:

    public int PropertyA
    {
        get
        {
            return //etc...
        }
        set
        {
            if (condition == true)
            {
                throw new ArgumentOutOfRangeException("value", "/* etc... */");
            }
            // ... etc
        }
    }
    
    0 讨论(0)
提交回复
热议问题