如果属性为null,哪个/什么时候抛出异常?

时间:2012-06-22 13:24:53

标签: c# exception exception-handling

我有以下课程:

class Foo
{
    public Foo()
        : this(new List<Bar>())
    {
    }

    public Foo(IEnumerable<Bar> bars)
    {
        Bars = bars;
    }

    public IEnumerable<Bar> Bars { get; set; }

    public Bar GetSingleBar(Data data)
    {
        // this method returns a single Bar from the Bars property above
        // this method returns the Bar which matches the data parameter
        // this method should not return null
        // this method throws a NoBarsFoundException if
        //   (a) Bars is empty or
        //   (b) no bar in Bars matches the data
    }
}

如果Barsnull,我该怎么办?我应该在Bars的setter中抛出异常,还是应该在GetSingleBar中抛出异常? (方法GetSingleBar是唯一使用Bars属性的方法。)

我应该抛弃ArgumentExceptionArgumentNullExceptionInvalidOperationException还是NoBarsFoundException

6 个答案:

答案 0 :(得分:5)

可能System.ArgumentNullException

  

将null引用(Visual Basic中的Nothing)传递给不接受它作为有效参数的方法时抛出的异常。

throw new ArgumentNullException("bars");

答案 1 :(得分:0)

这可能是不使用属性设置器的一个很好的理由,而是基于此问题的答案的方法:

Best practices: throwing exceptions from properties

这是因为该属性将以异常的形式变得可能不安全。

代替打扰它,ArgumentNullException是提供的参数为null时的标准(至少对于方法)。

如果您在设置之前尝试使用Bars,那么我会抛出一个InvalidOperationException来表示该对象未处于有效状态以满足该操作。< / p>

答案 2 :(得分:0)

我会说当Barsnull并且它永远不应该是null,那么你应该抛出InvalidOperationException,因为操作GetSingleBar是在对象的当前状态中无效,Bars是您的类的属性。

正如名称所示,

ArgumentNullException仅在参数为null时才会被抛出。

我会考虑制作Bars readonly(如果可能的话)。

答案 3 :(得分:0)

我会在方法GetSingleBar中抛出NoBarsFoundException。这样你就可以有另一种允许GetSingleBar为null的方法。

如果你总是想要阻止Bars为空,也许你应该在构造函数中设置它并将其设为私有?

答案 4 :(得分:0)

如果空集合导致对象不一致,我会抛出setter。

您永远不会知道将来会使用Bars的其他新方法。

答案 5 :(得分:0)

设置值时应抛出错误,因为这是发生“错误”的地方。

ArgumentNullException也是正确的错误消息。

我遇到的一个问题是你应该有一个set方法和一个只读属性,因为大多数程序员都不希望抛出异常。但是完全可以接受 - Properties and Exceptions