加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – IndexNotFoundException与NullReferenceException

发布时间:2020-12-15 08:06:48 所属栏目:百科 来源:网络整理
导读:我有以下代码尝试捕获空引用.然后抛出一个异常,更明确地说明了message属性中指定的错误. 它应该抛出什么类型的异常? IndexOutOfRangeException? var existing = this.GetByItemId(entity.ItemId); // int or longif (existing == null){ throw new IndexOu
我有以下代码尝试捕获空引用.然后抛出一个异常,更明确地说明了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对细节很轻,只是状态

Object reference not set to an instance of an object.

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

解决方法

我会为此使用自定义异常(像ItemNotFoundException这样的东西).

NullReferenceException或IndexOutOfRangeException可能由this.GetByItemId()内部的其他内容或某个框架中的其他内容抛出.

如果该项目未出现在集合中(例如,添加它),则呼叫者可能希望执行后续操作.使用您自己的异常允许调用者专门捕获该异常并做出相应的反应.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读