Consider a factory method that I may or may not control, passed to another class as a Func<T>:
// this.FactoryMethod is an external dependency passed into this class
// through constructor or property injection assume that it is not null
// but there is no guarantee that it will return a non-null reference.
Func<IModel> FactoryMethod;
public IModel GetPopulatedModel(int state, FileInfo someFile)
{
// Argument validation omitted for brevity...
// This operation could return null.
var model = this.FactoryMethod()
if (model == null)
{
throw new SomeException("Factory method failed to produce a value.");
}
// Safe to assign to properties at this point.
model.Priority = state;
model.File = someFile;
return model;
}
I would like to throw something that indicates the operation failed.
ArgumentNullException would be misleading because there is nothing wrong with the arguments:
The exception that is thrown when a null reference (Nothing in Visual
Basic) is passed to a method that does not accept it as a valid
argument.
InvalidOperationException doesn’t really seem to be on point:
The exception that is thrown when a method call is invalid for the
object’s current state.
It seems weird to consider a local variable to be part of the object's current state.
What would be good exception to throw? I’m surprised there is no OperationFailedException in System. Should I write my own exception, or is there a good one out there?
Two examples from the .NET Framework:
The SecurityTokenParameters.Clone Method throws an InvalidOperationException if the SecurityTokenParameters.CloneCore Method returns null.
The ClientCredentials.Clone Method throws a NotImplementedException if the ClientCredentials.CloneCore Method returns null.
CloneCore is essentially a factory method for clones of the current object.
I would use a NotImplementedException, because the factory method does not implement what is requested from it.