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 exceeding this length?
For example, this C# code:
public string MyProperty
{
get
{
return _MyBackingField;
}
set
{
if (value.Length > 100)
throw new FooException("MyProperty has a maximum length of 100.");
_MyBackingField = value;
}
}
I considered ArgumentException
, but it just doesn't seem right. Technically, it is a function - MyProperty_set(string value)
- so a case for ArgumentException
can be made, but it's not being called as a function to the consumer's eyes - it's on the right side of an assignment operator.
This question could probably also be extended to include all kinds of data validation done in property setters, but I'm particularly interested in the above case.