Best practices: throwing exceptions from properties

后端 未结 8 1917
生来不讨喜
生来不讨喜 2020-11-29 16:18

When is it appropriate to throw an exception from within a property getter or setter? When is it not appropriate? Why? Links to external documents on the subject would be he

8条回答
  •  隐瞒了意图╮
    2020-11-29 17:08

    This is all documented in MSDN (as linked to in other answers) but here is a general rule of thumb...

    In the setter, if your property should be validated above and beyond type. For example, a property called PhoneNumber should probably have regex validation and should throw an error if the format is not valid.

    For getters, possibly when the value is null, but most likely that is something you will want to handle on the calling code (per the design guidelines).

提交回复
热议问题