
An exception to end all exceptions
As we mentioned earlier, when you break an Apex limit, the Salesforce1 Platform throws an exception. It's actually a special type of exception called LimitException
. A LimitException
is a fatal one that you cannot handle gracefully with a try-catch
block. When LimitException
is thrown, all processing immediately ceases. The exception is appended to the debug log and an e-mail is sent out to the developer of that Apex class. Have faith though, it might not be possible to catch LimitException
, but it is very possible to avoid it.
Apex includes an entire class dedicated to listing and measuring limits. It's no coincidence that the name of this class is Limits
. It includes two methods for every limit in Apex. One method is to get the maximum number allowed for a limit, and the other method is to get the number that has already occurred. You can use the combination of both of these types of methods to ensure you never exceed the actual limit. The best part is by using this pattern, your code will easily adjust itself when the limits are relaxed in the future! This is the following code snippet:
//This query will never exceed the limit on QueryRows Integer queryRowLimit = limits.getLimitQueryRows(); Integer rowsAlreadyQueried = limits.getQueryRows(); Integer rowsRemaining = queryRowLimit - rowsAlreadyQueried; List<Account> accountQuery = [ Select Id From Account Limit :rowsRemaining ]; //Neither will this condensed one List<Contact> contactQuery = [ Select Id From Contact Limit :( limits.getLimitQueryRows()-limits.getQueryRows() ) ];
The previous code block demonstrates how easy it is to avoid hitting LimitException
. However, in doing so you might cause other issues in your code. In this example, it's possible that the first query results in the maximum number of rows causing the second query to have a limit of 0 and not resulting in any number!