Sub topic 11
Governor Limit Exceptions You Cannot Catch
This chapter assumes you know basic Apex syntax, SOQL and DML, and the idea of a transaction. It explains why some runtime failures skip your catch blocks, and what to do about them.
Two kinds of limit failure
Most Apex exceptions are ordinary objects. You can catch QueryException or DmlException and carry on. Governor limit violations are different. When code exceeds a per-transaction limit, the platform throws a System.LimitException. The runtime does not let you handle it.
A catch (Exception e) block will not intercept a LimitException. Neither will catch (System.LimitException e). The finally block does not run either. The platform stops the transaction and rolls back all uncommitted changes.
try {
for (Integer i = 0; i < 201; i++) {
// Each query counts toward the 100 SOQL query limit.
List<Account> accts = [SELECT Id FROM Account LIMIT 1];
}
} catch (Exception e) {
// Never reached for a LimitException.
System.debug('Caught: ' + e.getMessage());
} finally {
// Also skipped.
System.debug('Cleanup');
}This transaction fails with System.LimitException: Too many SOQL queries: 101. The debug statements never print.
Why the platform works this way
Limits protect the shared multitenant platform. If code could catch a limit failure and keep running, it could keep consuming resources. So the runtime ends the transaction as soon as a limit is crossed.
Some limit-related failures are catchable. A System.CalloutException for a callout to an unreachable host can be caught, and so can a DmlException. The uncatchable ones are the transaction-wide governor limits, such as:
| Limit | Typical message |
|---|---|
| SOQL queries issued | Too many SOQL queries: 101 |
| DML statements | Too many DML statements: 151 |
| DML rows | Too many DML rows: 10001 |
| CPU time | Maximum CPU time exceeded |
| Heap size | Apex heap size too large |
Check limits before you reach them
You cannot recover afterwards, so you prevent the failure. The Limits class reports usage and the maximum for the current transaction.
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'
);
}
}
}LimitGuardException is an ordinary custom exception, so callers can catch it and defer work, for example by enqueuing a Queueable. That gives you a controlled failure where the platform would give you an abrupt one.
Fix the cause
Guards are a safety net. The lasting fix is to write code that does not approach the limits.
- Move SOQL and DML out of loops. Collect records in a list or map, then run one statement.
- Query only the rows and fields you need.
- Move heavy work into asynchronous Apex, which has higher limits.
- Process large data sets with Batch Apex.
List<Account> toUpdate = new List<Account>();
for (Account a : [SELECT Id, Name FROM Account LIMIT 200]) {
a.Name = a.Name.trim();
toUpdate.add(a);
}
update toUpdate; // One DML statement, however many records.Testing
A test method that triggers a limit failure fails as a whole, because the exception cannot be caught inside it. Use Test.startTest() and Test.stopTest() to give the code under test a fresh set of limits. Then assert on Limits values to confirm your code stays well below the maximum.
Exercise
A method wraps a loop containing a SOQL query in try { } catch (Exception e) { }. The loop runs 150 times. What happens, and how should you fix it?
Show answer
The 101st query throws a LimitException, which the catch block cannot intercept. The transaction ends and its changes roll back. Fix it by moving the query out of the loop and querying once, using a collection or map for the results. You can also check Limits.getQueries() against Limits.getLimitQueries() before querying.