正解:C
Why a try/catch block is required:
In Salesforce, DML operations such as insert, update, delete, and upsert can throw exceptions due to issues like validation rule violations, field constraints, or sharing rule restrictions.
Using a try/catch block ensures that these exceptions are caught and handled gracefully, preventing the entire transaction from failing.
How to modify the code:
The update statement in the code can be wrapped in a try/catch block to catch and handle any exceptions that occur. For example:
apex
Copy code
public static void insertAccounts(List<Account> theseAccounts) {
try {
for (Account thisAccount : theseAccounts) {
if (thisAccount.website == null) {
thisAccount.website = 'https://www.demo.com';
}
}
update theseAccounts;
} catch (DmlException e) {
System.debug('DML Exception: ' + e.getMessage());
}
}
Why not the other options?
A). Implement the upsert DML statement:
upsert is used to either insert or update records based on an external ID or primary key. It does not inherently handle exceptions.
B). Implement Change Data Capture:
Change Data Capture (CDC) is used for tracking changes to data in real time and is unrelated to handling DML exceptions.
D). Remove null items from the list of Accounts:
While cleaning the input data is a good practice, it does not address the need for exception handling during DML operations.
References:
Apex Error Handling
DML Operations in Apex
最新のコメント (最新のコメントはトップにあります。)
正解は **C** です。
### 正解の解説
**C. DML の try/catch ブロックを実装します。**
問題文は「例外が適切に処理(Handle)されるようにするにはどうすればよいか」と問うています。
Apex開発において、データベース操作(DML)を行う際は、入力規則違反や重複ルール、必須項目の欠落など様々な理由で **`DmlException`** が発生する可能性があります。
* **現状の問題:** コードは `update theseAccounts;` を直接実行しています。もしエラーが発生すると、未処理の例外(Unhandled Exception)となり、トランザクション全体が停止し、ユーザーにはシステムエラー画面が表示されてしまいます。
* **解決策:** DML操作を **`try-catch` ブロック** で囲むことで、例外が発生してもプログラムをクラッシュさせずに捕捉し、エラーログを出力したり、ユーザーに分かりやすいメッセージを表示したりする「適切な処理」が可能になります。
<!-- end list -->
```apex
try {
update theseAccounts;
} catch (DmlException e) {
// 例外をキャッチして適切に処理(ログ出力など)
System.debug('エラーが発生しました: ' + e.getMessage());
}
```
[cite\_start]関連知識として、提供されたドキュメントの「例外処理の基本」[cite: 1022-1027] にも `try-catch` 構文の使用が記載されています。
-----
### 不正解の解説
**A. アップセット DML ステートメントを実装します。**
* メソッド名が `insertAccounts` であるにもかかわらず `update` を使用しているため、IDを持たない新規レコードが含まれている場合にエラーになります。`upsert` を使えばこの特定のエラーは回避できるかもしれません。
* しかし、`upsert` を使用しても、入力規則違反などの他の要因で **DML例外が発生する可能性は残ります**。`upsert` 自体は「例外処理(ハンドリング)」の機能ではないため、問題文の要件(例外を適切に処理する)に対する直接的な答えではありません。
**B. 変更データキャプチャを実装します。**
* これはデータの変更イベントを外部システム等に通知する機能であり、Apexコード内の例外処理とは無関係です。
**D. アカウントのリストから null 項目を削除します。**
* リスト内の `Account` オブジェクトが `null` である場合(`NullPointerException`)の対策にはなりますが、DML操作時のデータベースエラー(...