考虑一下我可能控制或不控制的工厂方法,将其传递给另一个类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;
}
Run Code Online (Sandbox Code Playgroud)
我想抛出一些表明操作失败的东西.
ArgumentNullException 会产生误导,因为这些论点没有错:
将null引用(在Visual Basic中为Nothing)传递给不接受它作为有效参数的方法时引发的异常.
InvalidOperationException 似乎并不是真的有点:
方法调用对于对象的当前状态无效时引发的异常.
考虑将局部变量作为其中一部分似乎很奇怪the object's current state.
抛出什么是好的例外?我很惊讶,没有OperationFailedException在System.我应该写自己的例外,还是有一个好的例外?
如果您认为可用的例外情况不充分,您可以随时创建自己的例外.
更新
虽然,我同意@TomTom和@dtb关于可能的选项.特别是NotImplementedException因为工厂确实没有实施