我有以下代码尝试捕获空引用.然后抛出一个异常,更明确地说明了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#中最无用的错误信息.