Java


JAVA.NULL.RET.UNCHECKED : Call Might Return Null (Java)

要旨

The return value of a method is frequently checked against null, but not here.

If null is dereferenced, Java runs into a NullPointerException. For this reason, programmers must ensure that the content of expressions dereferenced in their programs is never null.

CodeSonar provides two sets of warning classes covering various aspects of null value handling.

For the most comprehensive null pointer checking, enable both sets of warning classes: JAVA.NULL.* and JAVA.DEEPNULL.*

Strict and Non-Strict Checking

When JAVA_ANALYSIS_STRICT_MODE=No, warnings of this class will not be issued if there are indications that the possibility of a NullPointerException has been recognized and accounted for. For example, warnings will not be issued for code inside a try-catch block that explicitly catches NullPointerException, or for a JUnit test that is annotated as expecting this exception.

When JAVA_ANALYSIS_STRICT_MODE=Yes, warnings will be issued even in these cases.

プロパティ

クラス名 Call Might Return Null (Java)
日本語クラス名 Call Might Return Null (Java)
クラス分類 信頼性 (reliability)
ニーモニック JAVA.NULL.RET.UNCHECKED
カテゴリー
CWE CWE:252 Unchecked Return Value
CERT-Java CERT-Java:EXP00-J Do not ignore values returned by methods
対応言語 Java で利用可能です。
有効/無効設定 このワーニングクラスのチェックはデフォルトで有効になっています。チェックを無効にするにはプロジェクト設定ファイル (configuration file)に以下の WARNING_FILTER ルールを追加してください。
WARNING_FILTER += discard class="Call Might Return Null (Java)"

import java.util.HashMap;
import java.util.Map;

public class CheckReturnedValue {

    Map<String, String> map;
    public CheckReturnedValue(Map<String, String> map) {
        this.map = new HashMap<>();
        this.map.putAll(map);
    }

    private Object unknown() {
        return map.get("hello");
    }

    public void test0() {
        Object o = unknown();
        System.out.println("test0: " + o.toString()); // "Call Might Return Null (Java)" warning issued here 
    }

    public void test1() {
        Object o = unknown();
        if (o != null)
            System.out.println("test1: " + o.toString());
    }

    public void test2() {
        Object o = unknown();
        if (o != null)
            System.out.println("test2: " +o.toString());
    }

    public void test3() {
        Object o = unknown();
        if (o != null)
            System.out.println("test3: " +o.toString());
    }

    public void test4() {
        Object o = unknown();
        if (o != null)
            System.out.println("test4: " +o.toString());
    }
}

解決法

Check if the warning corresponds to a situation where null might actually be dereferenced at runtime. If that is the case, add a nullness check for the value being dereferenced, or change the logic of the code. Sometimes, a warning of this checker corresponds to a spurious nullness check, that can be removed.

関連のある設定ファイルパラメータ

設定ファイルの以下のパラメータがこのワーニングクラスのチェックに影響します。