I have the next code block that generates a limitException:

Account myAccount = new Account(Name = 'MyAccount');
Insert myAccount;

For (Integer x = 0; x < 150; x++) 
{Account newAccount = new Account (Name='MyAccountyyy' + x);
try {     
    Insert newAccount;
     System.debug ('inserted:'+x); }
catch (Exception ex) 
{System.debug ('EXCEPTION:'+ex) ;}


System.debug ('Last debug log');

If you see the debug, it will show only until: "Inserted: 149", but not "EXCEPTION:System.LimitException: Too many.... etc".

Why catch code block is not executed? Could someone explain me? Is not clear for me in documentation.


It's buried in the documentation a bit, but on Exception Class and Built-In Exceptions, there is this...

LimitException: A governor limit has been exceeded. This exception can’t be caught.

This is also outlined near the bottom of Exceptions in Apex

Exceptions that Can’t be Caught

Some special types of built-in exceptions can’t be caught. Those exceptions are associated with critical situations in the Lightning Platform. These situations require the abortion of code execution and don’t allow for execution to resume through exception handling. One such exception is the limit exception (System.LimitException) that the runtime throws if a governor limit has been exceeded, such as when the maximum number of SOQL queries issued has been exceeded. Other examples are exceptions thrown when assertion statements fail (through System.assert methods) or license exceptions.

When exceptions are uncatchable, catch blocks, as well as finally blocks if any, aren’t executed.

  • Thaks. Do you know where Can I see the list of those special types of buill-in exceptions? – alejandro Jul 9 at 19:15
  • I don't know if there is such a list. It might just be exceptions for limits, assertions, and licenses (as specified by the second documentation page I linked to). If that isn't the complete list, then those are certainly the most common, and I really wouldn't worry about it much more. – Derek F Jul 9 at 19:21

By design, System.LimitException cannot be caught in Apex code. So when that exception is generated, all your code is immediately exited.

This means you must design your code to not generate these exceptions by careful design. Generally, that means coding in bulk (multiple rows) and staying well below the limit. Google for articles on how to do this.

(There is the Limits class that allows you to check how close you are to a limit but I would not recommend trying to write code that is conditional on those values.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.