-2

I've created a custom exception class by extending Exception {} my question is, can I throw a custom exception inside a loop. does Apex consider throwing a custom exception as a DML operation

Below is the sample code

public class InfoException extends Exception {}
for (Id sObjectId : mySObjects.keySet()) {
if(Some condition check)
throw new InfoException('Bad Record.');
}
  • 1
    This appears to be an X-Y problem. You might want to post a question that actually explains what you're trying to do. – sfdcfox May 10 '18 at 6:15
  • "does Apex consider throwing a custom exception as a DML operation" - no. – Keith C May 10 '18 at 9:01
1

Yes, you can throw custom exception inside a loop.

Apex doesn't consider it as DML operation, since you are not performing a DML operation.

There are separate exceptions for DML operation which Salesforce provides. Refer Exception Class and Built-In Exceptions

| improve this answer | |
1

You can demonstrate for yourself by ruining this anonymous script:

class MyException extends Exception { }
try
{
    throw new MyException('msg');
}
catch (MyException e)
{
    system.assertEquals(0, Limits.getDmlStatements());
}
| improve this answer | |
0

You throw custom exception from a for loop by writing a try catch block

for (loop consition)
{

   try
   {
      if (condition)
      {
          throw new CustomException();
      }
   } catch (CustomException e)
   {
      e.setMessage('Some Error Message')
      Apex.addMessages(e);
      break;
   }
}

By Using break statement you can terminate the loop and the message will shown on the page

| improve this answer | |

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.