应该抛出异常是第一件事吗?

时间:2013-07-29 11:19:24

标签: c# validation exception exception-handling

验证用户输入的正确方法(如果有的话)是什么

这一个(首先抛出异常):

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");
    }
}

有指导方针吗?

3 个答案:

答案 0 :(得分:6)

没有真正的指南或规则,但第一个通常是首选,因为您可以移除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");

答案 1 :(得分:2)

与评论员一样,我会说如下:

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);

}

首先进行验证通常是我的偏好。您需要检查正确性或状态或参数。

答案 2 :(得分:1)

这对我来说完全一样,据我所知,没有指导方针。

为了便于阅读,我建议先把这个版本放在首位。

E.g。

if (...) throw new Exception();

do your thing