我有以下代码尝试捕获空引用.然后抛出一个异常,更明确地说明了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;
Run Code Online (Sandbox Code Playgroud)
还是一个NullReferenceException?
var existing = this.GetByItemId(entity.ItemId);
if (existing == null)
{
throw new NullReferenceException("The specified item does not exist.");
}
var price = existing.Price;
Run Code Online (Sandbox Code Playgroud)
或者,我们应该让异常运行吗?
var existing = this.GetByItemId(entity.ItemId);
var price = existing.Price; // NullReferenceException coming your way
Run Code Online (Sandbox Code Playgroud)
我们倾向于不做最后一个选项的原因是默认的NullReferenceException对细节很轻,只是状态
你调用的对象是空的.
说实话,这很可能是C#中最无用的错误信息.
我会为此使用自定义异常(有些事情ItemNotFoundException).
一个NullReferenceException或者IndexOutOfRangeException可能被某个内部this.GetByItemId()或框架内的其他东西抛出.
如果项目没有出现在集合中(例如添加它),调用者可能希望执行后续操作.使用您自己的异常允许调用者catch专门针对该异常并做出相应的反应.
带有您选择描述的自定义异常应该这样做:
if (existing == null)
{
throw new EntityMissingException("'existing' does not exist (ironic, isn't it?).");
}
Run Code Online (Sandbox Code Playgroud)