3

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?

Jez
  • 27,951
  • 32
  • 136
  • 233
  • possible duplicate of [What exceptions should be thrown for invalid or unexpected parameters in .NET?](http://stackoverflow.com/questions/774104/what-exceptions-should-be-thrown-for-invalid-or-unexpected-parameters-in-net) – mbeckish Mar 10 '15 at 18:07

4 Answers4

8

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");
Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
3

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.

Nikola Bogdanović
  • 3,206
  • 1
  • 20
  • 28
1

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.

boynoid
  • 116
  • 3
1

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");
}
  • You don't include a constructor that takes a `string`. In general if you inherit from `Exception` you should at least include constructors with parameters that match those of `Exception`. – juharr Mar 10 '15 at 18:12
  • That's a fair point. I was just providing a quick example not a copy-paste solution. – the_seeker_who Mar 10 '15 at 18:17