考虑一个我可能控制也可能不控制的工厂方法,作为 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;
}
我想抛出一些指示操作失败的东西。
ArgumentNullException
会产生误导,因为参数没有任何问题:
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
似乎并不正确:
The exception that is thrown when a method call is invalid for the object's current state.
将局部变量视为 the object's current state
的一部分似乎很奇怪.
抛出什么是好的异常?我很惊讶没有 OperationFailedException
在 System
.我应该编写自己的异常,还是有好的异常?
最佳答案
如果您觉得可供您使用的异常不足够,您可以随时创建自己的异常。
更新
虽然,我同意@TomTom 和@dtb 的可能选项。特别是 NotImplementedException
作为工厂确实没有实现
关于c# - 当工厂方法返回 null 时,我应该抛出什么异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9706390/