I have the following code that is trying to catch a null link. It then throws an exception with a clearer cause of the error specified in the message property.
Which exception should throw? 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;
or a NullReferenceException ?
var existing = this.GetByItemId(entity.ItemId); if (existing == null) { throw new NullReferenceException("The specified item does not exist."); } var price = existing.Price;
or if we just let the exception run the course?
var existing = this.GetByItemId(entity.ItemId); var price = existing.Price;
The reason that we usually donโt execute this last option is because, by default, a NullReferenceException illuminates the details and simply indicates
The reference to the object is not installed in the instance of the object.
Which, to be honest, could very well be the most useless error message in C #.
c # exception
Junto
source share