Thursday, July 03, 2008

Throw an Exception if Not Found

    /**
* Typical DAO/Service layer finder method.
* If unable to find the Object from the ID,
* throw an Exception instead of returning null.
*/
public Object findById(BigDecimal id)
throws NotFoundException, FindException {
try {
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
Object obj = new Object();
// populate the object...
return obj;
}
// throw a runtime exception instead of returning a null object
throw new NoSuchElementException("Object not found for ID: " + id);
} catch (SQLException e) {
throw new FindException(e);
}
}

See: Diagnosing Java Code: The Null Flag bug pattern

No comments: