IndexNotFoundException and NullReferenceException

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; // NullReferenceException coming your way 

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 #.

+7
c # exception
source share
3 answers

I would use a special exception for this (something like ItemNotFoundException ).

A NullReferenceException or IndexOutOfRangeException can be IndexOutOfRangeException something else inside this.GetByItemId() or somewhere in the Framework.

The caller may want to perform a subsequent action if the item is not displayed in the collection (for example, adds it). Using your own exception allows the calling caller to specifically detect this event and respond accordingly.

+9
source share

A custom exception with a description of your choice should do this:

  if (existing == null) { throw new EntityMissingException("'existing' does not exist (ironic, isn't it?)."); } 
+5
source share

NullReferenceException indicates that you want to access a null reference element. Usually you should never throw it (unless you use an interpreter or something like that).

If the entity parameter is a parameter, I would say that it is an ArgumentException . If you say that this should not happen under normal conditions, it is rather an InvalidOperationException .

+1
source share

All Articles