How to SalesForce

Can We Catch Governor Limit Exception in Try-Catch

Can We Catch Governor Limit Exception in Try-Catch

Introduction

Salesforce developers frequently face limitations while handling data and processing in Apex. The Governor Limit Exception is one of these common obstacles. This article explores if we can catch the Governor Limit Exception in try-catch blocks, providing actionable solutions and best practices for managing limits in Salesforce.

Read another blog on Show Record Details In Screen Flow.

Understanding Governor Limits in Salesforce

Governor limits are Salesforce’s way of enforcing resource usage restrictions to ensure that no code monopolizes shared resources. These limitations protect the system from excessive data usage and processing times, balancing performance across all users. However, when your Apex code exceeds these limits, a Governor Limit Exception occurs, halting execution.

Why Governor Limits Are Important

Governor limits protect Salesforce’s multi-tenant environment, preserving stability and ensuring that every user experiences optimal performance. These limits enforce responsible resource usage, preventing scenarios where one user’s code might degrade system-wide performance.

Common Types of Governor Limits

There are several types of governor limits that Salesforce developers encounter. Here are a few examples:

  1. SOQL Queries Limit: Salesforce enforces a limit on the number of SOQL queries a transaction can run.
  2. DML Statements Limit: Limits the number of DML operations (insert, update, delete) in a single transaction.
  3. CPU Time Limit: Restricts the maximum CPU time that Apex code can consume.
  4. Heap Size Limit: Places a limit on memory usage within a single transaction.

When these limits are exceeded, Salesforce throws a Governor Limit Exception, immediately stopping the code execution.

Can We Catch Governor Limit Exceptions?

A frequent question among Salesforce developers is whether they can catch Governor Limit Exceptions using try-catch blocks. Unfortunately, Salesforce doesn’t allow Governor Limit Exceptions to be caught in try-catch statements.

Why Try-Catch Doesn’t Work with Governor Limits

Salesforce enforces Governor Limit Exceptions to maintain platform stability and system integrity. Allowing developers to catch these exceptions could encourage inefficient code that continually reaches or exceeds limits. Consequently, Salesforce blocks Governor Limit Exceptions from being caught by try-catch blocks.

Alternative Approaches to Handle Governor Limits

Although you can’t catch Governor Limit Exceptions in a try-catch block, there are alternative strategies for avoiding them. By managing resource usage effectively, you can prevent your code from exceeding governor limits.

1. Use Bulk Processing

Bulk processing is a crucial method for working within governor limits, especially when dealing with large data sets. Here’s how to implement bulk processing:

  • Process Records in Batches: Instead of handling each record individually, process multiple records in a single batch.
  • Utilize `for` Loops Efficiently: Avoid SOQL queries and DML statements within `for` loops, as this can quickly reach limits.

Example:

List accountsToUpdate = new List();
for(Account acc : [SELECT Id, Name FROM Account WHERE SomeCondition = true LIMIT 100]) {
    acc.Name = 'Updated Account';
    accountsToUpdate.add(acc);
}
update accountsToUpdate;

Bulk processing helps minimize the number of SOQL and DML statements, thus staying within governor limits.

2. Optimize SOQL Queries

Optimizing SOQL queries is essential to avoid hitting the SOQL query limit. Follow these techniques:

  • Filter Data Efficiently: Only retrieve the necessary fields and records using WERE clauses.
  • Use `LIMIT`: Reduce query results by specifying a `LIMIT` clause where feasible.
  • Use Relationship Queries: Retrieve related data in a single query instead of making multiple SOQL calls.

Example:

List contacts = [SELECT Id, Name, Account.Name FROM Contact WHERE Account.Name = 'XYZ'];

These optimizations reduce the chances of exceeding SOQL query limits.

3. Implement Future Methods and Batch Apex

When handling large datasets or long-running processes, using asynchronous processing techniques like Future methods and Batch Apex can prevent Governor Limit Exceptions:

  • Future Methods: These allow certain processes to run asynchronously, offloading some processing to avoid governor limits in synchronous code.
  • Batch Apex: Batch Apex splits processing into smaller batches, ensuring that individual transactions don’t exceed governor limits.

Example of Future Method:

@future
public static void processAsync(String recordId) {
    // Process data asynchronously
}

Using asynchronous methods helps avoid synchronous governor limits by processing records in separate transactions.

Handling Specific Governor Limits

Each governor limit requires a specific approach to handle effectively. Here are some targeted strategies for common limits.

SOQL Queries Limit

Salesforce allows up to 100 SOQL queries in a single transaction. To avoid exceeding this limit:

  • Optimize Queries: Use `LIMIT` and only retrieve necessary fields.
  • Combine SOQL Statements: Use relationship queries instead of multiple individual queries.

DML Statements Limit

Salesforce limits DML operations to 150 per transaction. Minimize DML statements by:

  • Batching DML Statements: Group similar records in lists and perform DML once.
  • Use Upsert Statements: Where possible, use `upsert` to avoid separate insert and update statements.

CPU Time Limit

The CPU time limit restricts processing time, which can be exceeded in complex calculations. Reduce CPU usage by:

  • Optimizing Loops: Limit the use of nested loops and excessive calculations.
  • Using Map and Set Collections: Map and Set collections improve data access speed and reduce CPU usage.

Heap Size Limit

Exceeding heap size, often caused by large data structures, halts transactions. To handle heap size effectively:

  • Use Efficient Data Structures: Use Maps and Sets where appropriate.
  • Process Data in Chunks: Process large datasets in smaller parts to avoid excessive memory consumption.

Testing for Governor Limits

Testing is essential to ensure your code respects governor limits, particularly when handling high data volumes.

Use Test Classes to Simulate Limits

Salesforce allows you to simulate larger data volumes and observe governor limits within test classes. For example, create a test with multiple records to test bulk processing limits.

@isTest
public class AccountBulkTest {
    static testMethod void bulkTest() {
        List accounts = new List();
        for (Integer i = 0; i < 200; i++) {
            accounts.add(new Account(Name = 'Test' + i));
        }
        insert accounts;
    }
}

This testing method validates your code’s efficiency and ensures that it respects Salesforce governor limits.

Monitor Limits Using Debug Logs

Salesforce’s Debug Logs feature allows you to monitor resource consumption in real-time. Review debug logs for CPU usage, SOQL queries, and DML operations to identify any bottlenecks or excessive resource use.

Best Practices to Prevent Governor Limit Exceptions

Following best practices can reduce the risk of Governor Limit Exceptions and improve code performance.

Avoid SOQL and DML in Loops

Placing SOQL and DML statements inside loops is a common mistake that quickly leads to Governor Limit Exceptions. Process data outside of loops using bulk processing techniques.

Use Collections for Bulk DML

When handling DML statements, use lists or collections to process data in bulk. This approach minimizes the number of statements and stays within limits.

Optimize Code Logic

Refine your code logic to remove any unnecessary calculations or operations. This helps reduce CPU time and memory usage.

Leverage Caching

Store frequently accessed data in static variables to avoid redundant queries and processing.

Conclusion

While you can’t catch Governor Limit Exceptions in try-catch blocks, understanding and managing Salesforce governor limits is achievable. By using bulk processing, optimizing queries, and implementing asynchronous methods, you can prevent these exceptions. Embrace best practices and efficient coding techniques to maximize performance, reduce governor limit issues, and deliver a smoother user experience.

Picture of Uzair Zafar

Uzair Zafar

Certified Salesforce Consultant Uzair Zafar has over two years of experience developing commercial applications in Salesforce CRM. He is an expert at integrating Salesforce Sales Cloud, Service Cloud, and CPQ Cloud apps using web services, Workato, and Jitterbit. Uzair can create Scoping Documents, Use-case Documents, and demos and presentations in manufacturing, energy, and financial services.
Facebook
Twitter
LinkedIn