Java: can integer = null be set?

If this parameter exists in the database, I have a function that returns the ID number If not, null Is this begging for a null pointer exception? Negative signs are not allowed, but I think it would be clearer if non-existent parameters returned null instead of error codes like - 1 What's your opinion?

private Integer tidOfTerm(String name) throws sqlException {
    String sql = "SELECT tid FROM term_data WHERE name = ?";
    PreparedStatement prep = conn.prepareStatement(sql);
    prep.setString(1,name);
    ResultSet result = prep.getResultSet();

    if (result.next()) {
        return result.getInt("tid");
    }

    return null; // TODO: is this begging for a null pointer exception?
}

Solution

This is perfectly legal If you want to avoid NPE, throw a custom exception But don't return negative numbers If the caller does not check the return value, you will always have a problem But doing the wrong calculation (because the result ratio is multiplied by - 1) is definitely more difficult to debug than non - caught exceptions

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>