简体   繁体   中英

What exception should be thrown for an invalid ID?

I'm building an application services layer, and one of my methods accepts an entity's ID (integer) and returns the referenced entity. Although it seems like it should be simple, looking through the plethora of .NET exceptions, I'm not completely sure what exception I should throw if an entity with the given ID is not found (I don't want to just return null).

There is 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 namespace and/or custom exceptions?

First of all, System.Data is ADO.NET specific rather than ASP.NET specific.

Second of all, if you chose not to use ObjectNotFoundException , there's always ArgumentException which would allow you to do something like:

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

ArgumentOutOfRangeException - it's not the method's fault (as all your exceptions would suggest) that a wrong ID is supplied by a user.

ArgumentException is less verbose.

It depends on the context of the rest of your code. InvalidOperationException is to be used if a method is called when the application is not in a valid state for calling that method. ArgumentOutOfRangeException can be used if the application state is otherwise valid, but the id does not exist.

You could create your own exception and throw it for example InvalidEntityIdProvidedException.

class InvalidEntityIdProvidedException : Exception { }

And then call it like so:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM