Best practices: throwing exceptions from properties

后端 未结 8 1910
生来不讨喜
生来不讨喜 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

    It is almost never appropriate on a getter, and sometimes appropriate on a setter.

    The best resource for these sorts of questions is "Framework Design Guidelines" by Cwalina and Abrams; it's available as a bound book, and large portions of it are also available online.

    From section 5.2: Property Design

    AVOID throwing exceptions from property getters. Property getters should be simple operations and should not have preconditions. If a getter can throw an exception, it should probably be redesigned to be a method. Note that this rule does not apply to indexers, where we do expect exceptions as a result of validating the arguments.

    Note that this guideline only applies to property getters. It is OK to throw an exception in a property setter.

提交回复
热议问题