What exception to throw from a property setter?

后端 未结 7 2102
醉话见心
醉话见心 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 03:08

    I wouldn't throw an exception at all. Rather I would allow a string of any length and then have a seperate "Validate" method on the class that is called before saving. There are a number of scenarios particularly if you use databinding where throwing exceptions from property setters can get you in a mess.

    The trouble with throwing exceptions from property setters is that programmers forget to catch them. It kind of depends upon how clean you expect the data you are getting to be. In this case I would expect long string lengths to be common not exceptional and as such using an exception would be "flow control with exceptions".

    To quote from the Microsoft's Design Guidelines for Developing Class Libraries:

    Do not use exceptions for normal flow of control, if possible. Except for system failures and operations with potential race conditions, framework designers should design APIs so that users can write code that does not throw exceptions. For example, you can provide a way to check preconditions before calling a member so that users can write code that does not throw exceptions.

    0 讨论(0)
提交回复
热议问题