c# - 当工厂方法返回 null 时,我应该抛出什么异常?

标签 c# .net

考虑一个我可能控制也可能不控制的工厂方法,作为 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 的一部分似乎很奇怪.

抛出什么是好的异常?我很惊讶没有 OperationFailedExceptionSystem .我应该编写自己的异常,还是有好的异常?

最佳答案

如果您觉得可供您使用的异常不足够,您可以随时创建自己的异常。

更新 虽然,我同意@TomTom 和@dtb 的可能选项。特别是 NotImplementedException 作为工厂确实没有实现

关于c# - 当工厂方法返回 null 时,我应该抛出什么异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9706390/

相关文章:

c# - 如何在 MVC Web API 发布方法中将 ModelState 错误返回给 Kendo 网格?

c# - DBContext 不包含条目 : Cannot load related data 的定义

c# - 您可以修改父类(super class)的私有(private)字段吗?

c# - 如何使用 C#、.NET 将文本写入 Word 文件

.net - 使用表格副本

c# - 如何从字符串中去除无效字符

c# - 从 SQL Server 检索 blob 数据的最有效内存方式

c# - .net core 和 .net framework 4.6 的 Nuget 包兼容性

c# - 从多个 Texture2D 生成一个 Texture2D

.net - 如何使用 Visual Studio 2008 为 Pocket PC 2002 构建?