In Salesforce, it’s very important to handle exceptions in the Apex Code. Exceptions that are left unhandled can cause the entire process to fail. Like most programming languages, we use try/catch blocks to catch exceptions.
For Example,
Lead lead = new Lead();
insert lead;
Now, this is most likely to fail if the required fields aren’t set before the DML statement. And a Standard default expectation will be thrown that would give the message.
System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING
Syntax:
try {
Lead lead = new Lead();
insert lead;
} catch(DmlException e) {
System.debug(‘The following exception has occurred: ‘ + e.getMessage());
}
We put everything that’s related to the database commit in the try block, and to handle the unexpected exceptions, we write our custom handling logic in the catch block.
try {
Lead lead = new Lead();
insert lead;
} catch(DmlException e) {
System.debug(‘The following exception has occurred: ‘ + e.getMessage());
}
// This will get executed
System.debug(‘Statement after insert.’);
Now the advantage of using try/catch block is that even if the expectation occurred, the statement after the catch block will get executed.
Conclusion
As seen above, it’s very important to handle exceptions while writing Apex Code. That way we can control the flow of execution even if the code doesn’t perform as expected.
To learn more about Apex, check out some of my related articles below!
Additional Resources
- Dynamic Apex
- Ways to Deserialize Apex
- Apex Sharing
- Salesforce Developers: Exception Handling Example
- Salesforce Developers: Exceptions in Apex
Cover Photo by Shahadat Rahman on Unsplash