Which of following business methods are best, in return type and exception handling?
/**
* Finds an entity identified by given arguments.
* @param ...
* @returns found entity of {@code null} if not found.
*/
public MyEntity find1(...) {
try {
return query.getSingleResult();
} catch (final NoResultException nre) {
return null;
}
}
/**
* Finds an entity identified by given arguments. Note that this method
* may raise {@code NoResultException}.
* See {@link TypedQuery#getSingleResult()}.
* @param ...
* @returns found entity
*/
public MyEntity find2(...) {
...
return query.getSingleResult(); // may throw NoResultException
}
/**
* Finds an entity identified by given arguments.
* @param ...
* @returns an optional of found entity; never {@code null}
*/
public Optional<MyEntity> find3(...) {
try {
return Optional.of(query.getSingleResult());
} catch (final NoResultException nre) {
return Optional.empty();
}
}
All your variants are proper. They are all valid implementations to react to exceptions.
What can make them improper is a set of coding rules which tells you have to return optionals, catch exceptions always inside or whatever. So as long as you don't have such rules or you stick to them, you will be fine.