Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Tuesday, February 10, 2009 3:44 AM
I'm trying to find some guidelines for throwing exceptions in property setters.
Are there certain types of exceptions that are recommended within property setters.
For instance, because properties are intended to be used more like "data", it probably doesn't make sense to throw a ArgumentException, since an argument refers to a method argument. Even though property setters are really just methods, they are intended to be used as data.
When searching around on google, I wasn't really finding any guidelines on this.
Thanks for any thoughts or links on this.
Jeff
All replies (2)
Tuesday, February 10, 2009 2:26 PM ✅Answered
It's OK to use the Argument*Exception classes; the parameter name is "value" for a setter. Like you said, properties are just methods under the hood. The exceptions aren't meant to be seen by end-users, just for programmers to handle or debug. If I'm setting a property of a class library, I expect an ArgumentException to be thrown if I'm using the setter inappropriately. I think that's typical. I don't know that it really matters as long as you document what you're doing as "expected exceptions" for your method. There's a nice part of the XML comments that does this.
The .Net framework itself uses Argument*Exceptions on property setters (at least, in most of the cases I've seen).
Tuesday, February 10, 2009 2:29 PM ✅Answered
You can and should throw exceptions from property setters when necessary. You may use ArgumentOutOfRange() exception, or another of the argument based exceptions. Use "value" as the name of the argument.
Note: You should generally NOT throw exceptions from property getters.