3

We've received an Apex heap size too large error intermittently which we'd like to first capture and exit gracefully, and then to fix long term. Questions:

  1. Is it possible to catch a heap size exception through code?
  2. If so, what's the easiest way to re-create this exception in a test class, if it's even possible?
8

Is it possible to catch a heap size exception through code?

No.

If so, what's the easiest way to re-create this exception in a test class, if it's even possible?

You can easily create the exception by doing something like this:

String tooBig = '*'.repeat(6000000);
while(true) {
  tooBig = tooBig+'*';
}

Eventually, this code should crash with a heap error.


Edit: As an alternative, I suggest implementing a Warning System; you can then try to anticipate a problem and exit early. Something like this:

for(...) {
  if(Limits.getHeapSize() > Limits.getLimitHeapSize() * 0.9) {
    // report an error here then...
    break;
  }
}

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.