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.
Yes, throw the exception in the setter. If your code throws IllegalArgumentException at some later point in time, it would be confusing to the caller. From the docs: Thrown to indicate that a method has been passed an illegal or inappropriate argument.
As a rule of thumb, property getters and setters that are "late binding" should not throw exceptions, while properties with exclusively "early binding" should throw exceptions when the need arises.
The StackTrace property carries a stack trace that can be used to determine where the error occurs in the code.
You generally catch an exception in a method when you want your program to continue running. You throw an exception when you want a higher level method that is calling that method to handle the exception instead. For example, you might throw it all the way back to your Main method, which has a try..
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 } }
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