What exception should I use when a method returns an invalid result

I want to know what kind of exception (is there in .NET) I should throw when a called method returns an unexpected result.

For example, imagine a situation where I have a factory:

public abstract class Factory
    public A Create()
        var a = new A();
        var b = CreateDependencyOfA();
        a.Something = b.Property;

    protected abstract B CreateDependencyOfA();


I am documenting this class and making the assumption that CreateDependencyOfA does not return null (or whatever, i.e. for an integer, assuming the value is between 1 and 5).

What should I do when an implementation violates this contract (returning null in this case). Is there any type of exception in .NET designed for this purpose? I know there are some ArgumentExceptions, but they are, as I know, for the input parameters. Is there an equivalent for output parameters?

I'm asking this because I believe there is some sort of symmetry between the input and output parameters, but I don't know of any exceptions for the output.


source to share

2 answers

If a method returns a value that it should never return, it means that there is an internal logic error in your program. Errors of this kind (that is, situations that should never happen if the code is for spec) are best handled with assertions :

var dependency = Factory.CreateDependencyOfA();
Debug.Assert(dependency != null, "Factory returned null dependency.");


Note. Using assertions assumes that you are testing the output of your own method. In other words, you have Factory

all its implementations, that you have written all the methods, CreateDependencyOfA

and you know that those methods should not return null


If the implementation Factory

is a plugin written by someone else, you shouldn't use assertion. Instead, use InvalidOperationException

to indicate that the current state (namely, the implementation Factory

provided to you) is invalid.



You can check Code Contracts: http://msdn.microsoft.com/en-us/library/dd264808(v=vs.110).aspx

For example, your CreateDependencyOfA method might include a contract like:

Contract.Ensures(Contract.Result<B>() != null);




All Articles