This is something I’ve been thinking about a lot. When do I throw an exception? Do I program with exceptions? Do I catch those exceptions.
Consider this piece of code:
public Product GetProduct(int id) { //get the product, or null if not found Product p = //... return p; }
Now you can ask yourself the following question:
Is it ok to return null if the product is not found? After all, the calling layer assumes that we’ll be getting a Product, not a null.
So now the calling layer needs to check if the product != null.
It would be exceptional if no product was found.
So in my opinion you throw an exception if no product is found. And that get’s handled in the calling layer.
But on the other hand: if you would just return a null and test on that in the calling layer you would use less resources since exception throwing is expensive.
I’d still go with the first one since it goes better with my consume code thoughts.
But this is an agreement you need to make across your team, and across your API.