应该首先抛出异常吗
本文关键字:抛出异常 | 更新日期: 2023-09-27 18:25:15
验证用户输入的正确方法(如果有的话…)是什么
这个(首先抛出异常):
private void DisposeWorkFlowItem(WorkFlowItem item)
{
if (item == null)
{
throw new ArgumentException("work flow item must have value");
}
//TO DO: add a call to delete the task from worker service.
_workFlowItems.Remove(item);
_workFlowItemsStore.Delete(item);
}
或者这个(首先执行操作):
private void DisposeWorkFlowItem(WorkFlowItem item)
{
if (item != null)
{
//TO DO: add a call to delete the task from worker service.
_workFlowItems.Remove(item);
_workFlowItemsStore.Delete(item);
}
else
{
throw new ArgumentException("work flow item must have value");
}
}
有什么指导方针吗?
没有真正的指导方针或规则,但通常首选第一个,因为您可以删除else
,删除一级缩进。
private void DisposeWorkFlowItem(WorkFlowItem item)
{
if (item == null)
{
throw new ArgumentException("work flow item must have value");
}
//TO DO: add a call to delete the task from worker service.
_workFlowItems.Remove(item);
_workFlowItemsStore.Delete(item);
}
更少的缩进使代码更容易理解,尤其是在具有多个此类检查的场景中。
哦,当检查参数是否为null
时,通常会抛出一个ArgumentNullException
,参数名称为第一个参数:
throw new ArgumentNullException("item");
就像评论者所说的那样,我会按照如下方式进行:
private void DisposeWorkFlowItem(WorkFlowItem item)
{
if (item == null)
{
throw new ArgumentException("work flow item must have value");
}
//TO DO: add a call to delete the task from worker service.
_workFlowItems.Remove(item);
_workFlowItemsStore.Delete(item);
}
一开始做验证通常是我的偏好。您需要检查状态或参数的正确性。
这对我来说完全一样,据我所知,没有任何指导方针。
不过,为了便于阅读,我建议先把概念放在首位。
例如
if (...) throw new Exception();
do your thing