0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Salesforce】NullPointerExceptionとは?原因と対策まとめ

Posted at

1. NullPointerExceptionとは

NullPointerExceptionは、 null(値が存在しない状態)に対してメソッドやフィールドへアクセスしたとき に発生するエラー。

2. Salesforceにおける NullPointerException の例

例1: SOQL結果が存在しない

Account acc = [SELECT Id, Name FROM Account WHERE Id = :someId LIMIT 1];
System.debug(acc.Name); // ❌ レコードが無ければ例外発生

例2: Mapやリストの要素がnull

Map<Id, Account> accMap = new Map<Id, Account>();
System.debug(accMap.get(someId).Name); // ❌ get()の結果がnull
}

例3: 関連オブジェクトが未設定

Contact c = [SELECT Id, Account.Name FROM Contact LIMIT 1];
System.debug(c.Account.Name); // ❌ AccountがnullのときNPE

3. NullPointerExceptionに対しての対策

✅ if文でのnullチェック

最も基本的な対策は null を確認してから処理すること

if (c.Account != null) {
    System.debug(c.Account.Name);
}
🔹 ガード節(早期リターン)

nullチェックをコードの冒頭で行い、早めに処理を終了する

public void printAccountName(Contact c) {
    if (c.Account == null) {
        System.debug('Account未設定');
        return; // ガード節
    }
    System.debug(c.Account.Name);
}

✅ セーフナビゲーション演算子

nullになる可能性がある変数には初期値を入れておくと安全

System.debug(c?.Account?.Name); // nullなら安全にnullを返す

🔑 セーフナビゲーション演算子とは

セーフナビゲーション演算子は、 オブジェクトが null の場合でも安全にアクセスできる構文
通常の .(ドット演算子)は、対象が null だと NullPointerException を引き起こしますが、
?. を使うことで、nullなら例外を出さずに null を返す ことができる。

例1: 関連オブジェクト参照

Contact c = [SELECT Id, Account.Name FROM Contact LIMIT 1];

// 従来の書き方
if (c.Account != null) {
    System.debug(c.Account.Name);
}

// ?. を使った書き方
System.debug(c?.Account?.Name);

例2: メソッド呼び出し

String text = null;

// 従来の書き方
Integer len = (text != null) ? text.length() : null;

// ?. を使った書き方
Integer len2 = text?.length();

System.debug(len2); // null が返る

例3: ネストした参照

Account acc = [SELECT Id, Owner.Manager.Name FROM Account LIMIT 1];

// 従来の書き方
if (acc.Owner != null && acc.Owner.Manager != null) {
    System.debug(acc.Owner.Manager.Name);
}

// ?. を使った書き方
System.debug(acc?.Owner?.Manager?.Name);

✅ Collectionの空チェック

リストやマップを扱う場合は isEmpty() や containsKey() を利用する

if (!accList.isEmpty()) {
    System.debug(accList[0].Name);
}

if (accMap.containsKey(someId)) {
    System.debug(accMap.get(someId).Name);
}

✅ SOQL結果の存在確認

SOQLは結果が0件だと QueryException が発生する。例外処理や LIMIT を組み合わせて安全に扱う

try {
    Account acc = [SELECT Id FROM Account WHERE Name = 'Mike' LIMIT 1];
    System.debug(acc.Id);
} catch (QueryException e) {
    System.debug('レコードが見つかりませんでした');
}

✅ デフォルト値を設定

String industry = acc.Industry != null ? acc.Industry : '未設定';

4. NullPointerExceptionのまとめ

  • NullPointerException は「null にアクセスしようとした」時に発生するエラー
  • ApexでもSOQLや関連オブジェクト、Collection操作でよく発生する

主な対策としては

  1. nullチェック(if文 / ガード節)
  2. セーフナビゲーション演算子 ?.
  3. Collectionの空チェック(isEmpty() / containsKey())
  4. SOQL結果の存在確認(try-catch)
  5. デフォルト値の設定

📚 参考資料

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?