Salesforce Certified Platform Developer II — Question 225
A business requires that every parent record must have a child record. A developer writes an Apex method with two DML statements to insert a parent record and a child record.
A validation rule blocks child records from being created. The method uses a try/catch block to handle the DML exception.
What should the developer do to ensure the parent always has a child record?
Answer options
- A. Use addError() on the parent record if an error occurs on the child record.
- B. Set a database savepoint to rollback if there are errors.
- C. Use Database.insert() and set the allOrNone parameter to true.
- D. Delete the parent record in the catch statement when an error occurs on the child record DML operation.
Correct answer: B
Explanation
Setting a database savepoint allows the developer to roll back all changes made in the transaction if an error occurs, ensuring that the parent record is not saved without its required child record. The other options do not guarantee that the parent-child relationship is maintained; for example, using addError() would prevent the save but not fully handle the scenario of ensuring both records exist together.