.netnullreferenceexception

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?


Solution

  • 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://learn.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.