I have the following code that attempts to catch a null reference. It then throws an exception with a clearer reason for the error specified in the message property.
What type of exception should it throw? An 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, should we have just let the exception run its course?
var existing = this.GetByItemId(entity.ItemId);
var price = existing.Price; // NullReferenceException coming your way
The reason we tend not to do this last option, is that the default NullReferenceException is light on detail and just states
Object reference not set to an instance of an object.
Which, to be honest, could quite well be the most unhelpful error message in C#.
A NullReferenceException exception is thrown when you try to access a member on a type whose value is null . A NullReferenceException exception typically reflects developer error and is thrown in the following scenarios: You've forgotten to instantiate a reference type.
The best way to avoid the "NullReferenceException: Object reference not set to an instance of an object” error is to check the values of all variables while coding. You can also use a simple if-else statement to check for null values, such as if (numbers!= null) to avoid this exception.
The Null Reference Exception is not a major error, but one of the common ones and one of the basic and simple way to avoid the Null Reference Exception is to check the variable or property before moving ahead and accessing it. And a very basic way to do this is to check the variable within an if statement.
Use Null Coalescing to Avoid NullReferenceExceptions It works with all nullable data types. The following code throws an exception without the null coalescing. Adding “?? new List<string>()” prevents the “Object reference not set to an instance of an object” exception.
I would use a custom exception for this (some thing like ItemNotFoundException
).
A NullReferenceException
or IndexOutOfRangeException
might be thrown by something else inside of this.GetByItemId()
or in the Framework somewhere.
The caller might wish to perform a follow up action if the item does not appear in the collection (e.g. adding it).
Using your own exception allows the caller to catch
that exception specifically and react accordingly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With