vargonian
vargonian

Reputation: 3234

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.

Upvotes: 25

Views: 17558

Answers (5)

Mark
Mark

Reputation: 1371

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 { ... }

Upvotes: 2

Benjamin Baumann
Benjamin Baumann

Reputation: 4065

Personnally, I'd choose according to the GetVitalObject method contract. If this method should return a not null object I'd change it so it throws an exception in this case.

If you don't have control over the method or if returning a null value is correct (but not in your context) i'd go with a custom exception as Mark and Dmitry already said.

Upvotes: 0

Dmitry
Dmitry

Reputation: 14059

Consider to create your own Exception class inherited from the ApplicationException or from the Exception:

public sealed class MyException : Exception
{
    ...
}

Thus you will be able to control what kind of information to store in it.

Upvotes: 1

Gwendolyn Goetz
Gwendolyn Goetz

Reputation: 325

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.

Upvotes: 9

cbr
cbr

Reputation: 13660

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.

Upvotes: 14

Related Questions