I'm creating a simple CRUD class, let's call it MyItemManager. Its role is maintaining a collection of MyItem objects in a local database. I'm wondering which exception makes most sense to throw when trying to read a record that doesn't exist (by calling myItemManager.getItem(int id), and no such ID exists in the DB) Any tips / best practices? Thanks!
Asked
Active
Viewed 861 times
0
-
6**RecordNotFoundException** may be? – Rahul Apr 23 '13 at 10:11
-
1I'm with Kevin here. Just return `null`. – Thilo Apr 23 '13 at 10:15
-
1Related: http://stackoverflow.com/questions/175532/should-a-retrieval-method-return-null-or-throw-an-exception-when-it-cant-prod?rq=1 – Thilo Apr 23 '13 at 10:18
1 Answers
1
You may want to consider returning null instead of throwing exceptions. Exceptions should be reserved for "exceptional" circumstances.

Ankit
- 6,554
- 6
- 49
- 71

Kevin Brydon
- 12,524
- 8
- 46
- 76
-
-
1
-
1Technically, everything is an answer for this question! Therefore, this is not a proper question which meets the SO standards. – Rahul Apr 23 '13 at 10:14
-
1@KevinBrydon - sorry, I'm a little grumpy at the moment. With the edit I have no complaints :) – drew moore Apr 23 '13 at 10:20
-
1Of course, only return `null` if you know that the object does not exist, i.e. the DB returns an empty result set for the query. If you cannot connect to the db, for example, that would be an "exceptional circumstance". – Thilo Apr 23 '13 at 10:21
-
Thanks, I needed to be reminded of this. Going with null in case of empty query result (which was my main concern) and some exceptions in other cases. – oli.G Apr 30 '13 at 18:59