Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exception should I throw for an unexpected null value?

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.

like image 230
vargonian Avatar asked Dec 08 '15 18:12

vargonian


3 Answers

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.

like image 179
cbr Avatar answered Oct 03 '22 06:10

cbr


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.

like image 38
Gwendolyn Goetz Avatar answered Oct 03 '22 08:10

Gwendolyn Goetz


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 { ... }
like image 29
Mark Avatar answered Oct 03 '22 08:10

Mark