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
)
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With