In Salesforce Apex, exceptions arise from various factors such as invalid operations, surpassing governor limits, or encountering critical system errors. Apex provides a comprehensive framework to handle these exceptions, enabling applications to maintain stability and avoid unexpected failures.
How to Overcome Exceptions Effectively?
To overcome exceptions in Salesforce Apex, follow these strategies:
Use Try-Catch Blocks: Encapsulate risky code inside a try block and handle errors in the corresponding catch block.
Custom Exception Classes: Create meaningful custom exceptions to handle specific business logic scenarios.
Handle Governor Limits: Monitor and optimize resource usage to avoid governor limit exceptions.
Utilize Finally Block: Include a finally block to clean up resources, ensuring proper execution regardless of success or failure.
Log Errors: Use System.debug or custom logging frameworks to track and analyze exceptions.
Graceful User Feedback: Show user-friendly error messages instead of technical jargon.
Leverage Apex Continuations: For callouts, use asynchronous processes to manage limits efficiently.
Different types of Exception handling in Apex:
DML Exception:
When we are performing the DML such as insert, update, delete and we are not populating require fields during the insertion then error occurs.
public class ExceptionExample{ public static void exceptionErr(){ Contact conta1= new Contact(); conta1.FirstName='John'; insert conta1; } }
In above code the dmlexception error is occurred that is shown below.
To prevent this error, ensure that all mandatory fields are specified during the DML operation in the Apex code.
List Exception:
Whenever problem occurs in list in our apex code and accessing the element at an index that doesn’t exist in the list then ListException is occurred.
Public class ExceptionExamples { public static void exceptErr(){ List<Contact> contactList2 = [SELECT Id, Name FROM Contact WHERE Name ='SFDC Einstein']; system.debug('List Exception' +contactList2[0].Name); } }
In above code ListException error is occurred that is showing below.
To avoid this error we should check the size of list.
List<Contact> contactList2 = [SELECT Id, Name FROM Contact WHERE Name ='SFMC Einstein']; //check the list size if (contactList2.size()>0){ system.debug('List Exception' +contactList2[0].Name); }
Query Exception:
This error is occurred when there’s an issue with a SOQL. When SOQL query does not return any record and assigning that query in SObject then this error is generally occurred.
Public class ExceptionExamples { public static void exceptErr(){ Teacher__c teacherList1 = [SELECT Id, Name FROM Teacher__c WHERE Name ='Marc']; system.debug('teacherList'+teacherList1); } }
In above code queryException error is occurred that showing below.
To avoid queryException we should use the List We can update the line in above code as
LIST <Teacher__c> teacherList1 = [SELECT Id, Name FROM Teacher__c WHERE Name=’Marc’];
SObject Exception:
This occurs when you attempt to access a field on a queried SObject record, but that field was not included in the SELECT clause of the SOQL query.
Public class ExceptionExamples { public static void exceptErr(){ List<Teacher__c> teacherList1 = [SELECT Id FROM Teacher__c]; if(teacherList1.size()>0){ for(Teacher__c tch: teacherList1){ system.debug('teacherList1'+tch.Name); } } } }
In the code above, an SObject Exception occurs as demonstrated below.
To avoid this error we need to mention the field: Name in SOQL query which we want to access in apex code.
List<Teacher__c> teacherList = [SELECT Id, Name FROM Teacher__c];
Limit Exception:
Salesforce imposes governor limits to optimize resource utilization and maintain platform performance. If these limits are exceeded, a LimitException is triggered.
1.Too Many DML Statements: 151:
The error occurs when your Apex code exceeds the maximum number of allowed DML statements in a single transaction. Salesforce enforces governor limits to ensure fair resource usage among all the executing transactions. The limit for DML statements is 150.
Public class ExceptionExamples { public static void exceptErr(){ for(integer i= 0; i<151; i++){ Contact conta1 = new Contact(); conta1.LastName = 'Einstein'+ i; insert conta1; } } }
In above code limitException error is occurred that is shown below.
To prohibit the error, you can bulkify your code by performing the DML operation outside the loop.
Public class ExceptionExamples { public static void exceptErr(){ List<Contact> contactList23 = new List<Contact>(); for(integer i= 0; i<151; i++){ Contact conta1 = new Contact(); conta1.LastName = 'SFDC'+ i; contactList23.add(conta1); } if(contactList23.size()>0){ insert contactList23; } } } //In above code error will not occur
2.Too Many SOQL Queries: 101:
This error occurs in Salesforce when your Apex code or triggers exceed the permissible number of SOQL queries within a single transaction. The governor limit for SOQL queries in a transaction is 100.
Public class ExceptionExamples { public static void exceptErr(){ List<Contact> contactList2 = new List<Contact>(); for(integer i= 0; i<101; i++){ List<Contact> con = [SELECT Id, Name, Phone FROM Contact WHERE Name Like '%contact%']; system.debug('Exception'+con[0].Name); } } }
In above code limitException error is occurred that is showing below.
To avoid this error we need to move the soql query outside the for loop to avoid the too many soql query in apex code.
Public class ExceptionExamples { public static void exceptErr(){ List<Contact> con = [SELECT Id, Name,Phone FROM Contact WHERE Name Like '%contact%']; for (integer i = 0; i < 101; i++){ // You can use the con variable to access the query results system.debug('Exception ' + con[0].Name); } } }//In above code error will not occur.
NullPointer Exception:
A NullPointerException in Apex occurs when we trying to access a null object reference. This error indicates that our code is trying to perform an operation on an object that is not instantiated.
Public class ExceptionExamples { public static void exceptErr(){ Account acc; System.debug('NullPointerException'+acc.Name); } }
In above code NullPointerException error is occurred that is showing below.
To avoid this error, we need to assign the value before accessing in our code
if (acc != null) { System.debug(acc.Name); } else { System.debug('Account is null'); }
Reference:Exceptions in Apex
Conclusion
Exception handling is a critical aspect of Salesforce Apex development that ensures your applications are robust, reliable, and user-friendly. By proactively identifying potential failure points, implementing structured try-catch-finally blocks, and creating meaningful custom exceptions, you can build resilient solutions that gracefully handle unexpected scenarios. Always remember to log errors for debugging, optimize your code to respect governor limits, and provide clear feedback to users. With these practices, you can turn challenges into opportunities to enhance your code’s quality and maintainability. Happy coding!
Read more about different Salesforce topics: