-4

how can fix this nullpointerexception on sonarcube?

Sonar

Java Code:

  GeneratedKeyHolder generatedKeyHolder = new GeneratedKeyHolder();
        String sql = "Update users set enable=true where username=:username";
        SqlParameterSource paramSource = new MapSqlParameterSource().addValue("username", u.getUsername());
        namedParameterJdbcTemplate.update(sql, paramSource, generatedKeyHolder);
        try {
            return generatedKeyHolder.getKey().intValue();
A "NullPointerException" could be thrown; "getKey()" can return null.
        }
        catch (NullPointerException nl){
            return 0;
        }
    }
riki
  • 1,502
  • 5
  • 17
  • 45
  • 1
    By checking if `generatedKeyHolder.getKey()` is `null` before converting it to `int`. And please remove that `try-catch`... – Hulk Mar 30 '23 at 10:59

1 Answers1

-1
GeneratedKeyHolder generatedKeyHolder = new GeneratedKeyHolder();
    String sql = "Update users set enable=true where username=:username";
    SqlParameterSource paramSource = new MapSqlParameterSource().addValue("username", u.getUsername());
    namedParameterJdbcTemplate.update(sql, paramSource, generatedKeyHolder);
    try {
        Optional<Number> key = Optional.ofNullable(generatedKeyHolder.getKey());
        if(key.isEmpty())
            return null;
        else
            key.get().intValue();
    }
    catch (NullPointerException nl){
        return 0;
    }
Thomson Ignesious
  • 689
  • 1
  • 8
  • 25
  • If you really want to throw an Optional in there, replace the entire thing including the `try-catch` with `return Optional.ofNullable(generatedKeyHolder.getKey()).orElse(0);` (assuming that `getKey()` returns an `Integer`). – Hulk Mar 30 '23 at 11:13
  • it works thann you – riki Mar 30 '23 at 12:06
  • @Hulk this can return null as well, your code only returns 0 if it is null. In order to avoid try-catch only we have an Optional feature. – Thomson Ignesious Mar 31 '23 at 05:05
  • @ThomsonIgnesious I chose `0` as the default value because so did the OP in the `catch` block. Returning `null` is a change in behavior compared to the code in the OP, not sure if that is desired. – Hulk Mar 31 '23 at 05:08
  • @Hulk riki clearly mentioned in the code comment itself A "NullPointerException" could be thrown; "getKey()" can return null. – Thomson Ignesious Mar 31 '23 at 05:10