Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exception to throw from a property setter?

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.

like image 968
lc. Avatar asked Mar 11 '09 10:03

lc.


People also ask

Should setters throw exceptions?

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.

Should properties throw exceptions?

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.

Which of the following properties of exception class is used to find the code that cause the exception?

The StackTrace property carries a stack trace that can be used to determine where the error occurs in the code.

What is the purpose of throwing and catching an exception?

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..


1 Answers

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     } } 
like image 114
Richard Slater Avatar answered Oct 05 '22 08:10

Richard Slater