Mytutorialrack

Types of Exceptions in Salesforce

Exceptions are an inevitable part of Salesforce development and it is important to learn how to deal with them in the most effective manner possible. This is because an exception handles all the possibilities of errors that may occur in your application and allows it to handle errors in the most efficient manner possible. In this blog post, I will discuss the common exceptions that are used in Salesforce Apex, the causes of these exceptions and how to solve them by using try-catch blocks.

What are Exceptions in Apex?

An exception is an event that disrupts the normal flow of a program, typically due to errors in logic or unexpected input. In Apex, exceptions are a common part of development and can be managed using built-in mechanisms. Proper exception handling helps debug errors and ensures that other parts of the application remain unaffected.

Common Types of Exceptions in Salesforce Apex

1. Null Pointer Exception

A Null Pointer Exception occurs when your code tries to access an object or variable that hasn’t been initialized.

Example:

String str; 
Boolean bool = str.contains('name'); // This throws a Null Pointer Exception

How to Handle: Use a try-catch block to gracefully handle the error.

try {
Boolean bool = str.contains('name');
} catch (NullPointerException e) {
System.debug('Exception: ' + e.getTypeName());
}

2. List Index Out of Bound Exception

This exception arises when you attempt to access a list element using an index that doesn’t exist.

Example:

List<Integer> intList = new List<Integer>{100, 200, 300};
System.debug(intList[3]); // Throws List Index Out of Bound Exception

How to Handle:

try {
System.debug(intList[3]);
} catch (ListException e) {
System.debug('Exception: ' + e.getMessage());
}

3. Query Exception

A Query Exception occurs when a SOQL query does not return any records, or when it attempts to assign multiple rows to a single SObject.

Example:

Account acc = [SELECT Id, Name FROM Account WHERE Name = 'NonExistentName' LIMIT 1];
// Throws Query Exception if no record matches the query

How to Handle:

try {
Account acc = [SELECT Id, Name FROM Account WHERE Name = 'NonExistentName' LIMIT 1];
} catch (QueryException e) {
System.debug('Exception: ' + e.getMessage());
}

4. SObject Exception

An SObject Exception is thrown when attempting to access fields not included in a SOQL query.

Example:

Account acc = [SELECT Id FROM Account LIMIT 1];
String description = acc.Description; // Throws SObject Exception

How to Handle:

try {
String description = acc.Description;
} catch (SObjectException e) {
System.debug('Exception: ' + e.getMessage());
}

5. DML Exception

This exception occurs when a DML operation (e.g., insert, update, delete) fails due to reasons like missing required fields or validation rule violations.

Example:

Account acc = new Account();
insert acc; // Throws DML Exception due to missing required fields

How to Handle:

try {
insert acc;
} catch (DmlException e) {
System.debug('Exception: ' + e.getMessage());
}

6. Limit Exception

Salesforce imposes Governor Limits to ensure optimal performance. A Limit Exception occurs when these limits are exceeded, such as performing too many DML operations or SOQL queries in a single transaction.

Example:

for (Integer i = 0; i < 200; i++) {
Account acc = new Account(Name = 'Account ' + i);
insert acc; // Exceeds the DML limit
}

How to Handle: Optimize your code to avoid exceeding limits. Use bulk operations and asynchronous methods to stay within limits.

Best Practices for Handling Exceptions in Apex

  1. Use Specific Try-Catch Blocks:
    Handle specific exceptions individually rather than using a generic Exception handler.
  2. Log Exception Details:
    Use methods like getMessage(), getTypeName(), and getStackTraceString() to log and debug exception details.
  3. Optimize Code to Prevent Exceptions:
    Validate inputs and preemptively handle potential edge cases to reduce exceptions.
  4. Test for Governor Limits:
    Regularly test your code against Salesforce Governor Limits to ensure compliance.
  5. Always Use Fallback Logic:
    Ensure your application can gracefully recover from exceptions without disrupting the user experience.

Checkout our Platform Developer 1 Certification Course

Looking to kickstart your career as a Salesforce Developer and ace the Platform Developer I Certification? I’ve got the perfect course to help you achieve your goals!

This comprehensive course is designed to:

  • Equip you with the skills needed to become a successful Salesforce Developer.
  • Cover all the key concepts and practical scenarios for the Platform Developer I Certification.
  • Provide hands-on exercises to solidify your knowledge and build real-world confidence.
  • Include expert tips and strategies to help you prepare effectively and pass your certification on the first attempt.
  • Guide you through building a strong foundation in Apex, Visualforce, and Salesforce Lightning Components.

Don’t miss this opportunity to invest in your future! Enroll now and take the first step toward becoming a certified Salesforce professional.

Conclusion

Understanding and handling exceptions in Apex is vital for developing reliable Salesforce applications. By familiarizing yourself with these common exceptions and following best practices, you can ensure your code is robust, efficient, and prepared for unexpected errors.

Share:

Recent Posts