gpt4 book ai didi

c# - IndexNotFoundException 与 NullReferenceException

转载 作者:太空狗 更新时间:2023-10-29 19:59:29 25 4
gpt4 key购买 nike

我有以下代码试图捕获空引用。然后它会抛出异常,并为消息属性中指定的错误提供更明确的原因。

应该抛出什么类型的异常? 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)。

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

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

关于c# - IndexNotFoundException 与 NullReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33520690/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com