Salesforce is a powerful platform that allows businesses to manage their customer relationships, automate processes, and build custom applications. However, like any other platform, errors and exceptions can occur during development or runtime. Understanding these exceptions is crucial for developers and administrators to debug and resolve issues effectively.
In this blog post, we will explore the different types of exceptions in Salesforce, provide detailed explanations, and include examples to help you understand how to handle them.
What is an Exception in Salesforce?
An exception is an event that occurs during the execution of a program and disrupts the normal flow of instructions. In Salesforce, exceptions are typically thrown when an error occurs in Apex code, such as attempting to divide by zero, accessing a null object, or exceeding governor limits.
Exceptions in Salesforce can be broadly categorized into two types:
- Standard Exceptions: These are built-in exceptions provided by Salesforce.
- Custom Exceptions: These are user-defined exceptions created by developers to handle specific scenarios.
Standard Exceptions in Salesforce
Salesforce provides a set of standard exceptions that are commonly encountered during development. Below is a list of the most frequently thrown shown standard exceptions, along with examples:
1. DmlException
This exception is thrown when a DML operation (e.g., insert, update, delete, upsert) fails due to validation rules, required field violations, duplicate rules, or other constraints.
Example:
Explanation:
- The DmlException provides methods like getDmlId() and getDmlStatusCode() to retrieve details about the failed record and the specific error.
- In this example, the Account object requires a Name field. If it’s missing, the exception is thrown.
2. NullPointerException
This exception occurs when you attempt to dereference a null variable (e.g., calling a method or accessing a property on a null object).
Explanation:
- The variable s is null, and calling s.length() results in a NullPointerException.
- Always initialize variables before using them to avoid this exception.
3. ListException
This exception is thrown when you attempt to access an invalid index in a list or modify a list while iterating over it.
Example:
Explanation:
- Lists in Apex are zero-indexed, so accessing nums[3] throws a ListException because the list only has indices 0, 1, and 2.
- Always check the size of the list before accessing elements by index.
4. QueryException
This exception occurs when a SOQL query fails, such as when no records are returned for a single-record assignment or when the query is invalid.
Example:
Explanation:
- If the query returns no records and you’re assigning the result to a single SObject variable, a QueryException is thrown.
- Use List<SObject> or check for empty results to avoid this exception.
5. SObjectException
This exception occurs when you attempt to access a field that wasn’t retrieved in a SOQL query or when you access a field on a null record.
Example:
Explanation:
- The Name field was not included in the SOQL query, so attempting to access it throws an SObjectException.
- Always ensure that all required fields are included in your queries.
6. StringException
This exception occurs when performing invalid string operations, such as using an invalid index in substring().
Explanation:
- The substring() method is called with an index (10) that exceeds the length of the string (5), resulting in a StringException.
- Always validate string lengths and indices before performing operations.
7. TypeException
This exception occurs when there’s an invalid typecast, such as attempting to cast a String to an Integer.
Example:
Explanation:
- The obj variable is a String, and casting it to an Integer throws a TypeException.
- Use proper type-checking methods like instanceof before casting.
8. MathException
This exception occurs during invalid arithmetic operations, such as division by zero.
Example:
Explanation:
- Dividing by zero is mathematically undefined and throws a MathException.
- Always validate denominators before performing division.
Also Read – Test Class Best Practices in Salesforce
9. CalloutException
This exception occurs when an HTTP callout fails, such as due to a timeout, invalid endpoint, or network issue.
Example:
Explanation:
- The callout fails because the endpoint is invalid or unreachable, resulting in a CalloutException.
- Always validate endpoints and handle network errors gracefully.
10. SecurityException
This exception occurs when a user attempts to perform an operation they don’t have permission for, such as accessing a field or object without the necessary FLS (Field-Level Security) or CRUD permissions.
Example:
Explanation:
- The SecurityException is thrown when the user lacks the necessary permissions to perform the operation.
- Always check user permissions before performing sensitive operations.
Are you preparing for the Salesforce AI Certifications? Check out the Salesforce certification practice set here
FAQs
1. Why might a NullPointerException occur even if you check for null?
NullPointerException can slip through null checks if:
- Method Chaining: You call a method on a null object in a chain (e.g., acc.Owner.Name where Owner is null).
- Unboxing: You unbox a null wrapper object (e.g., Integer num = (Integer)myNullObject;).
2. Why might a CalloutException occur even if the external API is working fine?
CalloutException can occur due to:
- In a sandbox/Prod, callouts to non-whitelisted endpoints are blocked.
- The callout exceeds the 10-second timeout limit (or the custom timeout set in the code).
3. what is a Mixed DML exception?
In Salesforce, a Mixed DML Exception occurs when you’re trying to perform DML (Data Manipulation Language) operations on both sObject types that belong to different sets of objects: “Setup” objects and “Non-Setup” objects, within the same transaction.
Conclusion
Standard exceptions in Salesforce are powerful for handling errors in Apex code. By understanding these exceptions and their use cases, you can write more robust and maintainable code. Always handle exceptions gracefully to improve the user experience and ensure your application runs smoothly.