Sub topic 11
Governor limit exceptions you cannot catch
This chapter assumes you can write try, catch, and finally blocks and that you know the main governor limits, such as 100 synchronous SOQL queries and 150 DML statements per transaction. Most Apex exceptions can be handled. A governor limit violation cannot, and the difference affects how you design error handling.
What a LimitException is
Salesforce is multitenant, so many customers share the same resources. Governor limits keep one transaction from using too much of them. When your code goes past a limit, the runtime throws a System.LimitException, for example:
System.LimitException: Too many SOQL queries: 101This exception looks like the others. It extends Exception and has a message and a stack trace. The difference is that the runtime does not let your code intercept it.
Catch and finally blocks are skipped
When a LimitException is thrown, the runtime ends the transaction immediately. Three things follow:
- No
catchblock runs, includingcatch (Exception e). - No
finallyblock runs. - All database changes made in the transaction are rolled back.
The following code shows this. Run it as anonymous Apex in an org where the query limit applies:
try {
for (Integer i = 0; i < 101; i++) {
List<Account> rows = [SELECT Id FROM Account LIMIT 1];
}
} catch (Exception e) {
System.debug('catch ran: ' + e.getMessage());
} finally {
System.debug('finally ran');
}The loop runs its 101st query and the transaction fails. The log contains the unhandled LimitException, and neither debug statement appears.
Why you cannot work around it
Some developers try to catch the exception by its specific type:
try {
// code that might exceed a limit
} catch (LimitException e) {
// This does not run when a governor limit is exceeded.
}This compiles, which is misleading, but the block does not run when a real governor limit is hit. Catching Exception has the same result. You also cannot save the transaction by splitting work into a second try block after the limit is exceeded, because the transaction is already over.
You can still throw your own exception whose class name or message mentions limits, and you can catch that. That has nothing to do with the platform's limit enforcement, so it does not help here.
The practical rule: check limits before you hit them
Because you cannot recover, you avoid the failure. Apex gives you the Limits class, which reports how much of each limit the current transaction has used. Each limit has a pair of methods: one for current usage and one for the maximum.
| Resource | Used so far | Maximum |
|---|---|---|
| SOQL queries | `Limits.getQueries()` | `Limits.getLimitQueries()` |
| Rows returned by SOQL | `Limits.getQueryRows()` | `Limits.getLimitQueryRows()` |
| DML statements | `Limits.getDmlStatements()` | `Limits.getLimitDmlStatements()` |
| Rows changed by DML | `Limits.getDmlRows()` | `Limits.getLimitDmlRows()` |
| CPU time in milliseconds | `Limits.getCpuTime()` | `Limits.getLimitCpuTime()` |
| Heap size in bytes | `Limits.getHeapSize()` | `Limits.getLimitHeapSize()` |
You can wrap these checks in a helper and throw your own exception before the platform does. Your own exception is catchable, so callers can decide what to do.
public class LimitGuard {
public class LimitGuardException extends Exception {}
public static void requireQueries(Integer needed) {
Integer remaining = Limits.getLimitQueries() - Limits.getQueries();
if (remaining < needed) {
throw new LimitGuardException(
'Need ' + needed + ' queries but only ' + remaining + ' remain in this transaction'
);
}
}
public static void requireDml(Integer needed) {
Integer remaining = Limits.getLimitDmlStatements() - Limits.getDmlStatements();
if (remaining < needed) {
throw new LimitGuardException(
'Need ' + needed + ' DML statements but only ' + remaining + ' remain in this transaction'
);
}
}
}A caller can then handle the failure in a controlled way:
try {
LimitGuard.requireQueries(3);
// run the three queries here
} catch (LimitGuard.LimitGuardException e) {
System.debug('Skipping optional work: ' + e.getMessage());
}This pattern fits optional work, such as enrichment or logging, that you can skip when resources are low. It does not fit work that must happen. For that, the right fix is to reduce resource use.
Preventing the common causes
Most limit failures come from the same few patterns. Fix these first.
- SOQL or DML inside a loop. Query once before the loop, store the results in a
Map, and look values up inside the loop. Collect records into a list and run one DML statement after the loop. - Triggers that assume one record. A trigger receives up to 200 records per chunk. Write every trigger handler to process the whole
Trigger.newcollection. - Unbounded queries. A query without a selective
WHEREclause or aLIMITcan return more than 50,000 rows, which exceeds the row limit. - Large collections held in memory. Iterate a SOQL query with a
forloop, as infor (Account a : [SELECT Id FROM Account]). The platform retrieves records in batches of 200, which reduces heap use. - Expensive loops. Nested loops over large lists drive up CPU time. Replace inner searches with map lookups.
Here is a bulk-safe version of a common mistake:
public class ContactCounter {
public static void updateCounts(List<Account> accounts) {
Map<Id, Integer> counts = new Map<Id, Integer>();
for (AggregateResult ar : [
SELECT AccountId acctId, COUNT(Id) total
FROM Contact
WHERE AccountId IN :accounts
GROUP BY AccountId
]) {
counts.put((Id) ar.get('acctId'), (Integer) ar.get('total'));
}
for (Account a : accounts) {
a.NumberOfEmployees = counts.containsKey(a.Id) ? counts.get(a.Id) : 0;
}
}
}It runs one query no matter how many accounts it receives. The version with a query inside the loop would fail at the 101st account.
Limits in tests and other contexts
Limits apply per transaction, and each execution context has its own counters. A few details matter in practice:
- Inside a test method,
Test.startTest()andTest.stopTest()give the code under test a fresh set of limits. Setup work beforestartTestis counted separately. - Asynchronous Apex such as Queueable and Batch jobs runs in new transactions with different limits. For example, the SOQL limit is 200 queries instead of 100 for asynchronous code, and the heap limit is larger. The async chapter covers how errors there are reported.
- Limits are enforced even when you use
Database.insert(records, false). Partial success only changes how record-level validation errors are reported. It does not relax DML statement or row limits.
A test cannot verify a LimitException with try and catch, for the same reason production code cannot catch one. Instead, test that your code stays within limits by asserting on Limits values after running it with a large data set:
@IsTest
private class ContactCounterTest {
@IsTest
static void usesOneQueryForManyAccounts() {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 200; i++) {
accounts.add(new Account(Name = 'Acct ' + i));
}
insert accounts;
Test.startTest();
ContactCounter.updateCounts(accounts);
Integer queriesUsed = Limits.getQueries();
Test.stopTest();
Assert.areEqual(1, queriesUsed, 'Expected a single aggregate query');
}
}Reading a limit failure
When a limit failure does happen, the debug log is your main source of information. Look for these lines:
LIMIT_USAGE_FOR_NSentries near the end of the log, which list how much of each limit was used.- The
FATAL_ERRORline, which names the limit and the class and line number where it was exceeded. - The stack trace, which shows the call path, such as a trigger calling a helper class that queries inside a loop.
The line number points to the statement that crossed the limit. The statement that caused the problem may be earlier in the call path, for instance a trigger that fires another trigger which also runs queries.
Exercise
A method contains try { ...101 queries in a loop... } catch (Exception e) { log(e); } finally { cleanup(); }. What happens when the 101st query runs, and what should you change?
Show answer
The runtime throws a System.LimitException that cannot be caught, so neither the catch block nor the finally block runs. The transaction ends with an unhandled error and all its changes roll back. Fix the cause by moving the query out of the loop (query once and use a Map), and optionally add a Limits check, such as comparing Limits.getQueries() with Limits.getLimitQueries(), before optional work.
Exercise
Which statement is correct? (a) Database.insert(records, false) avoids the DML statement limit. (b) catch (LimitException e) lets you continue the transaction. (c) Limits.getQueries() returns the number of SOQL queries used so far in the transaction.
Show answer
(c). Option (a) is wrong because allOrNone=false only changes how record-level failures are reported, and option (b) is wrong because the catch block does not run for governor limit violations.