Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why JPA uses javax.persistence.NoResultException

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.

like image 598
ps-aux Avatar asked Jun 04 '14 18:06

ps-aux


1 Answers

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.

like image 92
mabi Avatar answered Oct 06 '22 07:10

mabi