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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With