I have a SQL statement that I expect will return one row, because I am passing the primary key. So my choices are to
- Wrap the queryForObject in a try/catch, catching EmptyResultDataAccessException, and returning null
- Change the call to queryForList, and unwrap the List and (hopefully) return the 1st element, or null.
I read somewhere the cathing an EmptyResultDataAccessException, since it extends runtime exception, is a bad practice.
But I can't see anything wrong with it.
I would be interested in hearing opinions
2 Answers
Most of the time I have run into this(mvc/ws) I let the exception be thrown but handle the exception in an exception resolver. The problem with returning null is that an application is depending on it and further down the road and you would have to do a null check later rather than at the time it is expected to be there. This can cause problems because not all developers may be doing the null check when required and then you could run into npe later. Depending on what type of application you are writing there are several ways to catch and handle the exception using an exception resolver. By using an exception resolver you can handle each exception differently and provide feedback to the user.
Here is one way to do it using spring mvc. This way you can put a general message to a user if the object with the primary key does not exist.
I think it's perfectly acceptable to catch that exception. It's the only Spring exception I catch that I can recall, but I have valid use cases for trying to find a record that is potentially not in existence.