I've been a .NET developer for over a decade so here's a shameful question I've never known the answer to. I get it--if an argument is null, I can throw an ArgumentNullException. A NullReferenceException will be thrown if I try to dereference a null value.
But what if I have code like the following:
var someVitalObject = someServiceReference.GetVitalObject();
if (someVitalObject == null)
{
throw new IDontKnowWhatException(); // what exception should I throw here?
}
Now, this isn't necessarily a problem with the service for which an exception should have been thrown earlier.
It's hard to say without seeing more context, but perhaps System.InvalidOperationException
?
The exception that is thrown when a method call is invalid for the object's current state.
I typically use ArgumentNullException for objects passed into a function. Anything else null related I use InvalidOperationException. In specialized cases I'll create a custom exception if it makes sense to.
I would only use System.ArgumentNullException when directly checking a method parameter, not when validating the result of some call.
The type of exception I throw depends greatly on the context. But in this case I would probably go for a custom exception like:
public class VitalObjectNotAcquiredException : Exception { ... }
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