Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reasons to throw a NullReferenceException explicitly?

I'm cleaning up some legacy code and I have found methods which explicitly throw a NullReferenceException (e.g.: when checking if some properties of a class are null, or checking configuration). As this type of exception is thrown by CLR in case of a null reference, this seems like a very poor choice of an exception for an application to throw explicitly.

My question is - are there any reasons for which a NullReferenceException would be a good choice for an exception to throw explicitly from code?

like image 374
Marcin Seredynski Avatar asked Oct 19 '11 13:10

Marcin Seredynski


2 Answers

The documentation for NullReferenceException implies that you shouldn't throw it from an application:

Note that applications throw the ArgumentNullException exception rather than the NullReferenceException exception discussed here.

And I am sure I've seen guidance elsewhere (can't find any at the moment-> it is here https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/using-standard-exception-types) that you should avoid throwing exception types that the runtime throws (although I'm about to link to something which shows the runtime throwing an "application" exception)


If you're checking properties within a method, before proceeding, it sounds like you might want to replace them with InvalidOperationException:

InvalidOperationException is used in cases when the failure to invoke a method is caused by reasons other than invalid arguments.

Being in the incorrect state for the method call sounds like it fits this definition.

like image 53
Damien_The_Unbeliever Avatar answered Oct 12 '22 02:10

Damien_The_Unbeliever


No, there is no reason to throw a NullReferenceException.

You always have some more information about the reason for the error, so you should throw an exception that conveys that information.

If you for example get a null reference as an argument where it's not allowed, you would throw an ArgumentException or ArgumentNullException instead.

like image 20
Guffa Avatar answered Oct 12 '22 01:10

Guffa