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