IndexNotFoundException与NullReferenceException

时间:2015-11-04 11:29:19

标签: c# exception

我有以下代码尝试捕获空引用。然后抛出一个异常,更明确地说明了message属性中指定的错误。

它会抛出什么类型的 异常? IndexOutOfRangeException

var existing = this.GetByItemId(entity.ItemId); // int or long
if (existing == null)
{
    throw new IndexOutOfRangeException("The specified item does not exist.");
}

var price = existing.Price;

NullReferenceException

var existing = this.GetByItemId(entity.ItemId);
if (existing == null)
{
    throw new NullReferenceException("The specified item does not exist.");
}

var price = existing.Price;

或者,我们应该让异常运行吗?

var existing = this.GetByItemId(entity.ItemId);
var price = existing.Price; // NullReferenceException coming your way

我们倾向于不做最后一个选项的原因是默认的NullReferenceException是详细的,只是状态

  

对象引用未设置为对象的实例。

说实话,很可能是C#中最无用的错误信息。

3 个答案:

答案 0 :(得分:9)

我会为此使用自定义异常(有些像ItemNotFoundException)。

NullReferenceExceptionIndexOutOfRangeException可能会被this.GetByItemId()内的其他内容或框架中的其他内容抛出。

如果项目没有出现在集合中(例如添加它),调用者可能希望执行后续操作。 使用您自己的异常允许调用者明确catch该异常并做出相应的反应。

答案 1 :(得分:5)

带有您选择描述的自定义异常应该这样做:

 if (existing == null)
    {
        throw new EntityMissingException("'existing' does not exist (ironic, isn't it?).");
    }

答案 2 :(得分:1)

NullReferenceException表示您要访问空引用的成员。通常你不应该抛弃它(除非你实现了解释器或类似的东西)。

如果entity是参数,那么我会说这是ArgumentException。如果你说这在正常情况下永远不会发生,那么这就是InvalidOperationException