示例代码:
public class ElementList
{
// some code...
public ElementList (Element owner)
{
// some code...
}
public void Add (Element e)
{
if (e == owner) // cannot add child which will be self-parent
{
throw new SomeException (); // main problem here
}
childList.Add (e);
}
}
现在应该抛出什么样的例外?如果您建议自定义例外,请告诉我一个好名字。
答案 0 :(得分:1)
这看起来像是ArgumentException的工作。最好将它子类化并创建自己的 - 像ParentElementArgumentException这样的名称就足够明了 - 所以你可以测试这个特定的条件以及一般的arg异常(比如有人传递的不是元素)。 / p>
答案 1 :(得分:1)
我建议ArgumentException
,因为异常将由您的参数e
if (e == owner) // cannot add child which will be self-parent
{
throw new ArgumentException(/* Include more exception details here */);
}
答案 2 :(得分:1)
简而言之: ArgumentException
可以解决问题。但是,抛出您可能在代码中轻松管理的异常并不是一个好习惯。
我建议重写你的代码,如:
public void Add (Element e)
{
if (e != owner)
{
// Not the owner, do your operation
childList.Add (e);
}
else {
// Log error message or display warning to user
}
}
但是,如果您想要继续处理异常情况,那么代码可能如下所示:
if (e == owner) // cannot add child which will be self-parent
{
throw new ArgumentException("Can not add child which will be self-parent");
}
修改:作为参考,您当然可以使用MSDN article 进行详细了解。