Is not usage of javax.persistence.NoResultException
violation of the basic principles of exception usage in Java?
Exceptions should not be used to control normal flow of program. Returning zero result from a database query seems to me pretty standard (not exceptional) situation. One which will be handled by calling code anyway.
Note that the javadoc for NoResultException states:
Thrown by the persistence provider when Query.getSingleResult() or TypedQuery.getSingleResult()is executed on a query and there is no result to return.
By using getSingleResult()
you indicate you know there's going to be exactly one result. Not more (see NonUniqueResultException
), not less. So I'd argue that the absence of a result is indeed an exceptional circumstance.
If you're unsure about the amount of data that will be returned, use getResultList().
But you're not alone with your distate for this part of the JPA API. This post indicates that the only really valid use for getSingleResult()
is returning a scalar value, pointing out that NoResultException
is a unchecked exception and quoting Bloch's Effective Java, Item 40:
Use checked exceptions for recoverable conditions and runtime exceptions for programming errors.
Unfortunately the JPA 2.0 spec (or any other for that matter) doesn't explain the reasoning behind this choice.
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