Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

handling zero records found

 
Mohit Sinha
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

In a database intensive application where there is lot of retrieval happening there could be every possibility of "no records found" scenario may be due to missing data. Typically in java we indulge in a lot of paranoid programming where in we always have something like (if results != null or !results.empty()).
But this is really not a complete solution. Ideally the user should get something like "No records found for your entered criteria" exception or some other message.
So wanted to understand if a scenario like "zero records found" is handled like an exception. Is it a popular approach to treat the same as exception in the object oriented world once this is received from the database side as "zero records" is not an error in the database world.
If there is any other way of handling "zero records" scenario in the java side do post your thoughts.

Mohit
 
Vinod K Singh
Ranch Hand
Posts: 198
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"zero records" is not an error in the database world

Thats why JDBC drivers does not throw NoDataFoundException. It is the responsibility to data access layer to throw such an exception if need be. So just create a custom exception and throw it at appropriate time.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49733
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can handle an empty ResultSet the same way you handle a zero-length array. Using "while (rs.next()){...}" will simply not do anything.
If you want specific handling for a zero return, I am not quite sure; you could try "isAfterLast()" but there is bound to be a better solution.
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34837
369
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mohit,
I don't think zero records found should be an exception when asking for a list. Exceptions are for things you don't expect to occur. Zero records is a legitimate scenario. I usually loop through the result set putting all the results in a list anyway. At the end it is easy to see if the list was empty.

If I am only looking for one record and it isn't there, that would be a reason to throw an exception. In that case, I use the idiom:


This is similar to how entity beans deal with things. If you ask for a list, you get an empty list. If you ask for a bean by primary key, you get an exception.

Note that a result set will never be null when returned from JDBC so there is no need to check that.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic