对于无效 ID 应该抛出什么异常?

What exception should be thrown for an invalid ID?

我正在构建应用程序服务层,我的方法之一接受实体的 ID(整数)和 return 引用的实体。虽然它看起来应该很简单,但通过大量的 .NET 异常,我不完全确定如果找不到具有给定 ID 的实体我应该抛出什么异常(我不想只是 return null).

ObjectNotFoundException, but that is in the System.Data namespace which means it should be ASP.NET-specific, which this isn't. There is NullReferenceException, but it's recommended that programmers not throw that as it is "internal", and I'm not sure whether it's quite right in this scenario anyway. I don't want to throw the generic Exception. So, what specific exception class would make the most sense to throw here? As this is an app services layer method (thus quite abstract), would it be a good idea for me to limit myself to exceptions in the System.SystemException命名空间and/or自定义异常?

首先,System.Data 是 ADO.NET 特定的而不是 ASP.NET 特定的。

其次,如果您选择不使用 ObjectNotFoundException,总有 ArgumentException 允许您执行以下操作:

throw new ArgumentException("Given Id not found.", "id");

这取决于其余代码的上下文。如果在应用程序未处于调用该方法的有效状态时调用该方法,则将使用 InvalidOperationException。如果应用程序状态有效但 id 不存在,则可以使用 ArgumentOutOfRangeException。

您可以创建自己的异常并将其抛出,例如 InvalidEntityIdProvidedException。

class InvalidEntityIdProvidedException : Exception { }

然后这样称呼它:

if ( entityId < 0 ) {
    throw new InvalidEntityIdProvidedException("The entity id provided is incorrect");
}

ArgumentOutOfRangeException - 用户提供了错误的 ID 不是方法的错(正如所有异常所暗示的那样)。

ArgumentException 不那么冗长。