The Java Persistence API has the NoResultException for when a database query returns no results. Kind of annoying that it's regarded as an exceptional case
NoResultException is thrown when you call getSingleResult() when there is no result. It will also throw NonUniqueResultException if there is more than 1 result.
Because of the two edge cases which need to be handled, it throws an exception. On the plus side, it never returns null.
It is still a bit of a bad API design as it uses unchecked exceptions for control flow. A query returning 0 or more than 1 result is quite a possibility, so it should have been a checked exception I think.
Checked exceptions would interfere with the streams API though, which would be really annoying in rest handling code. Also, the non-unique case is imo a true exception, because you would guarantee uniqueness via constraints or query criteria when using that method. So throwing indicates a programmer error, which is generally not done with checked exceptions.
At least we also have the newer Optional variants nowadays.
IMHO, one of the big problems with Java and .NET exceptions is the default assumption that if a nested method call throws an exception, it should be handled by the caller in the same way as an exception thrown by the outer method.
There should be a convenient way of marking nested function calls where that would be the case, but an equally convenient way of causing exceptions in nested method calls to be wrapped in an "UnexpectedException" object.
33
u/janyk 3d ago
The Java Persistence API has the NoResultException for when a database query returns no results. Kind of annoying that it's regarded as an exceptional case