Working with Salesforce limits
How to work with Salesforce limits?
We can use Limits class to check how many resources we have left. Check example on the next page!
You probably have seen a similar message before:
15:38:46.90 |EXCEPTION_THROWN|[101]|System.LimitException: Too many SOQL queries: 101
15:38:46.90 |FATAL_ERROR|System.LimitException: Too many SOQL queries: 101And you probably know that you cannot prevent it, how can we do something about it?
We can use Limits class to check how many resources we have left. Check example on the next page!
In the case of SOQL rows, we can use this code:
if (Limits.getLimitQueries() - Limits.getQueries() == 0) {
throw new CustomLimitException();
}Now instead of uncatchable System.LimitException, code will throw a custom one which can be handled!
When is it useful? You shouldn’t enclose all your code in the try/catch blocks from now on. This trick is useful in scenarios when you know that the operation you perform can hit a limit, and you want to account for that. A good example would be processing big amounts of data:
if (Limits.getLimitHeapSize() - Limits.getHeapSize() < 500000) {
System.enqueueJob(new RunNexJob(dataChunk));
}This code will create new Job (new transaction) for the rest of data if we are close to HeapSize limit.
See the link in the description for more information!


