从属性获取器抛出 NotSupportedException
我听说从财产获取者那里抛出异常是不合适的,并且我理解这个基本原理背后的原因。然而,以下情况让我感到困惑:想象一下,您正在编写一个旨在适应多个不同平台的外观:
public interface IFacade
{
int SomeProperty { get; set; }
}
现在想象一下平台 X
和 Y
支持 SomeProperty< /code> 本身,但该平台
Z
没有。难道从平台 Z
适配器中的 getter 抛出 NotSupportedException
不应该是告诉用户该平台的特定情况不支持该功能的正确方法吗?
I have heard it is inappropriate to throw exceptions from property getters, and I understand the reasons behind this rationale. However, the following situation is puzzling me: Imagine you are writing a facade meant to adapt to several different platforms:
public interface IFacade
{
int SomeProperty { get; set; }
}
Now imagine that platform X
and Y
support SomeProperty
natively, but that platform Z
does not. Shouldn't throwing NotSupportedException
from the getter in platform Z
's adapter be the right way to tell users that the functionality is not supported in that platform's particular case?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只要这种行为被记录下来,就没有任何问题。如果您担心处理异常的必要性,可以引入
SupportsSomeProperty
属性。然而,这可能会破坏界面。As long as this behavior is documented there is nothing wrong about it. If you are concerned with necessity to handle the exception, you can introduce
SupportsSomeProperty
property. However, this can blow up the interface.由于您知道无法捕获异常(对此您无能为力,该平台不受支持!),或者如果捕获了异常则无法处理,所以最好退出程序并显示一条错误消息,指出当前平台不支持。
异常通常用在可以捕获和处理的地方,或者在发生错误时意外抛出的地方。如果您发现程序在平台
z
上运行的错误,如果程序无法继续,则退出该程序。Since you know that exception can't be caught (there's nothing you can do about it, the platform isn't suppported!), or handled if it is caught, it would be better to exit the program and display an error message saying that the current platform is not supported.
Exceptions are generally used in places where they can be caught and handled, or are thrown unexpectedly in event of error. If you catch an error that the program is running on platform
z
, then exit the program, if it cannot continue.