What exception should I use for unexpected null value?

I have been a .NET developer for over a decade, so this is a shameful question that I never knew about. I get this - if the argument is null, I can raise 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 is not necessarily a problem with the service for which the exception should have been sent earlier.

+7
c # exception exception-handling
source share
6 answers

It's hard to say without seeing more context, but perhaps a System.InvalidOperationException ?

An exception that is thrown when a method call is invalid for the current state of an object.

+5
source share

I would use System.ArgumentNullException only when directly checking a method parameter, and not when checking the result of some call.

The type of exception I throw is highly context sensitive. But in this case, I will probably go with a special exception, for example:

 public class VitalObjectNotAcquiredException : Exception { ... } 
+1
source share

I usually use ArgumentNullException for objects passed to a function. Everything related to null values, I use InvalidOperationException. In special cases, I will create my own exception if that makes sense.

+1
source share

I would throw a System.NullReferenceException . Or, if you are unhappy with this, you can extract a more specialized null-reference exception type from this for your own purposes.

0
source share

Consider creating your own Exception class, inherited from ApplicationException or from Exception :

 public sealed class MyException : Exception { ... } 

Thus, you can control what information is stored in it.

0
source share

In general, I would choose the GetVitalObject method according to the contract. If this method should return a non-null object, I would modify it, so it throws an exception in this case.

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

0
source share

All Articles