Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exception should I throw when method returns invalid result

Tags:

c#

.net

exception

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

For example, imagine situation where I have factory:

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

    protected abstract B CreateDependencyOfA();
} 

I document that class and create assumption that CreateDependencyOfA does not return null(or anything else, i.e. for integer assuming that value is between 1 and 5).

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

I am asking this because I believe there is some kind of symmetry between input and output parameters but I do not know any exceptions for output.

like image 468
Szymon Knop Avatar asked Oct 02 '14 21:10

Szymon Knop


1 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 (i.e. situations that must never happen if the code is designed to specification) are best handled by assertions:

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

Note: use of assertions assumes that you are checking the output of your own method. In other words, you own the Factory and all its implementations, that you wrote all the CreateDependencyOfA methods, and that you know that these methods must not return null.

If an implementation of the Factory is a plug-in written by somebody else, you should not use an assertion. Instead, use InvalidOperationException to indicate that the current state (namely, the Factory implementation supplied to you) is invalid.

like image 148
Sergey Kalinichenko Avatar answered Sep 27 '22 20:09

Sergey Kalinichenko