Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which exception should I throw if the requested entity does not exist in Db? [closed]

Imagine a method, that attempts to retrieve an entity which SHOULD exist in the Db in terms of Business Logic (for a specific case).

When I try to retrieve it from the Db via my Repository and if I get back null, which exception I should throw? (I was thinking ObjectNotFoundException)

like image 203
pencilCake Avatar asked Jan 11 '13 09:01

pencilCake


People also ask

When should I throw exception C#?

If you really don't want a calling method to ignore your error you need to throw an exception. The caller will have to explicitly write code then to handle the problem.

How to avoid exceptions?

Another way to avoid exceptions is to return null (or default) for most common error cases instead of throwing an exception. A common error case can be considered a normal flow of control. By returning null (or default) in these cases, you minimize the performance impact to an app.

Does not exist exception C#?

FileNotFoundException is responsible for occurring at times when we pass a file or are attempting to execute input or output operations with file but the file does not exists. Other reasons could be, incorrect file name, or incorrect source link. File Exists method can be used to avoid this exception.

When to Use exceptions?

Exceptions should be used for situation where a certain method or function could not execute normally. For example, when it encounters broken input or when a resource (e.g. a file) is unavailable. Use exceptions to signal the caller that you faced an error which you are unwilling or unable to handle.


2 Answers

One could argue whether an exception is needed at all; why not return an empty collection or null?

The kind of Exception you should use depends on the way you are using exceptions in the application.

The first thing you might consider is whether or not it is a functional error (should the user correct something) or a technical error (did the developers make a mistake).

Another thing you should consider is what is natural for the caller of the method.

like image 176
Emond Avatar answered Oct 24 '22 19:10

Emond


I wouldn't throw an exception for this sort of scenario, just handle the null return value instead. It's not really a good idea to start using exceptions to control application flow.

If the entity should definitely be there then you could handle the null value in the Business Layer and throw a custom domain exception e.g. EntityNotFoundException, however, I wouldn't put that sort of logic at repository level.

like image 22
James Avatar answered Oct 24 '22 17:10

James