5

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?

1 Answer 1

9

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;
  }
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .