Exception not being caught; System.FinalException: Cannot modify a collection while it is being iterated












1















Why is this Exception not being caught?



I read that System.LimitException is not caught but didn't see anywhere about System.FinalException.



Non-Working Code



@AuraEnabled
public static List<RecordType> getRecordTypes() {

try {

String sObjectType = 'Task';

List<RecordType> recordTypes = RecordTypeRepository.getBySObjectType(sObjectType);

return removeGenericTaskRecordType(recordTypes);

} catch (Exception e) {

String message = ErrorMessage.formatExceptionMessage(e, 'There was an error running NewTaskFormController getRecordTypes.');
System.debug(message);
throw new AuraHandledException(message);
}
}


public static List<RecordType> removeGenericTaskRecordType(List<RecordType> recordTypes) {

RecordType genericTask = RecordTypeRepository.getById(RecordTypeRepository.GENERIC_TASK_ID);

Integer genericTaskIndex = recordTypes.indexOf(genericTask);

for (RecordType recordType: recordTypes) {
recordTypes.remove(genericTaskIndex );
}


return recordTypes;
}


What I've Tried




  • The same code structure (try-catch) just a different exception and it does get caught.
    "common.apex.runtime.impl.ExecutionException: List index out of bounds: -1


Working-Code Example



 public static List<RecordType> removeGenericTaskRecordType(List<RecordType> recordTypes) {

RecordType genericTask = RecordTypeRepository.getById(RecordTypeRepository.GENERIC_TASK_ID);

Integer genericTaskIndex = -1;

recordTypes.remove(genericTaskIndex);

return recordTypes;
}









share|improve this question





























    1















    Why is this Exception not being caught?



    I read that System.LimitException is not caught but didn't see anywhere about System.FinalException.



    Non-Working Code



    @AuraEnabled
    public static List<RecordType> getRecordTypes() {

    try {

    String sObjectType = 'Task';

    List<RecordType> recordTypes = RecordTypeRepository.getBySObjectType(sObjectType);

    return removeGenericTaskRecordType(recordTypes);

    } catch (Exception e) {

    String message = ErrorMessage.formatExceptionMessage(e, 'There was an error running NewTaskFormController getRecordTypes.');
    System.debug(message);
    throw new AuraHandledException(message);
    }
    }


    public static List<RecordType> removeGenericTaskRecordType(List<RecordType> recordTypes) {

    RecordType genericTask = RecordTypeRepository.getById(RecordTypeRepository.GENERIC_TASK_ID);

    Integer genericTaskIndex = recordTypes.indexOf(genericTask);

    for (RecordType recordType: recordTypes) {
    recordTypes.remove(genericTaskIndex );
    }


    return recordTypes;
    }


    What I've Tried




    • The same code structure (try-catch) just a different exception and it does get caught.
      "common.apex.runtime.impl.ExecutionException: List index out of bounds: -1


    Working-Code Example



     public static List<RecordType> removeGenericTaskRecordType(List<RecordType> recordTypes) {

    RecordType genericTask = RecordTypeRepository.getById(RecordTypeRepository.GENERIC_TASK_ID);

    Integer genericTaskIndex = -1;

    recordTypes.remove(genericTaskIndex);

    return recordTypes;
    }









    share|improve this question



























      1












      1








      1








      Why is this Exception not being caught?



      I read that System.LimitException is not caught but didn't see anywhere about System.FinalException.



      Non-Working Code



      @AuraEnabled
      public static List<RecordType> getRecordTypes() {

      try {

      String sObjectType = 'Task';

      List<RecordType> recordTypes = RecordTypeRepository.getBySObjectType(sObjectType);

      return removeGenericTaskRecordType(recordTypes);

      } catch (Exception e) {

      String message = ErrorMessage.formatExceptionMessage(e, 'There was an error running NewTaskFormController getRecordTypes.');
      System.debug(message);
      throw new AuraHandledException(message);
      }
      }


      public static List<RecordType> removeGenericTaskRecordType(List<RecordType> recordTypes) {

      RecordType genericTask = RecordTypeRepository.getById(RecordTypeRepository.GENERIC_TASK_ID);

      Integer genericTaskIndex = recordTypes.indexOf(genericTask);

      for (RecordType recordType: recordTypes) {
      recordTypes.remove(genericTaskIndex );
      }


      return recordTypes;
      }


      What I've Tried




      • The same code structure (try-catch) just a different exception and it does get caught.
        "common.apex.runtime.impl.ExecutionException: List index out of bounds: -1


      Working-Code Example



       public static List<RecordType> removeGenericTaskRecordType(List<RecordType> recordTypes) {

      RecordType genericTask = RecordTypeRepository.getById(RecordTypeRepository.GENERIC_TASK_ID);

      Integer genericTaskIndex = -1;

      recordTypes.remove(genericTaskIndex);

      return recordTypes;
      }









      share|improve this question
















      Why is this Exception not being caught?



      I read that System.LimitException is not caught but didn't see anywhere about System.FinalException.



      Non-Working Code



      @AuraEnabled
      public static List<RecordType> getRecordTypes() {

      try {

      String sObjectType = 'Task';

      List<RecordType> recordTypes = RecordTypeRepository.getBySObjectType(sObjectType);

      return removeGenericTaskRecordType(recordTypes);

      } catch (Exception e) {

      String message = ErrorMessage.formatExceptionMessage(e, 'There was an error running NewTaskFormController getRecordTypes.');
      System.debug(message);
      throw new AuraHandledException(message);
      }
      }


      public static List<RecordType> removeGenericTaskRecordType(List<RecordType> recordTypes) {

      RecordType genericTask = RecordTypeRepository.getById(RecordTypeRepository.GENERIC_TASK_ID);

      Integer genericTaskIndex = recordTypes.indexOf(genericTask);

      for (RecordType recordType: recordTypes) {
      recordTypes.remove(genericTaskIndex );
      }


      return recordTypes;
      }


      What I've Tried




      • The same code structure (try-catch) just a different exception and it does get caught.
        "common.apex.runtime.impl.ExecutionException: List index out of bounds: -1


      Working-Code Example



       public static List<RecordType> removeGenericTaskRecordType(List<RecordType> recordTypes) {

      RecordType genericTask = RecordTypeRepository.getById(RecordTypeRepository.GENERIC_TASK_ID);

      Integer genericTaskIndex = -1;

      recordTypes.remove(genericTaskIndex);

      return recordTypes;
      }






      apex exception collection iteration try-catch






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jan 3 at 16:35







      shmuels

















      asked Jan 3 at 16:25









      shmuelsshmuels

      796




      796






















          2 Answers
          2






          active

          oldest

          votes


















          4














          Your exception is not being caught because FinalException is not catchable. Neither are LimitException nor AssertException.



          You can quickly check for yourself if a given type of exception is catchable using an anonymous script like the following:



          try
          {
          throw new FinalException();
          }
          catch (Exception pokemon)
          {
          system.debug('Cannot catch em all');
          }


          Note that in general:




          • you should know what specific types of exception you are expecting and catch only those

          • it is better to avoid the exception entirely if it is preventable, even if it can be caught






          share|improve this answer
























          • It's also very avoidable; just using a normal for loop instead of for-each fixes the problem.

            – sfdcfox
            Jan 3 at 16:29











          • Yeah I thought that might be a bit of a separate question though. Why can I not catch FinalException seems like one for which we might get plenty of dupes over the years.

            – Adrian Larson
            Jan 3 at 16:30











          • Yeah, I'm kind of surprised this is not a duplicate (but apparently not?). Good to have an answer like this available.

            – sfdcfox
            Jan 3 at 16:35











          • Thank you. For some reason the Docs only mention LimitException and AssertException but not FinalException.

            – shmuels
            Jan 3 at 18:31








          • 1





            It does not prove the difference between those two, but in general, if a standard exception is not caught with this script, you can assume it is by design.

            – Adrian Larson
            Jan 3 at 18:42



















          2














          Answer from @Adrian is good, but on a different note the reason why you're getting this error was because your code attempts to modify a collection while it is being iterated in the for each loop, which is not allowed. Read about Read-only Collections




          If you need to modify the List or Set while iterating over it, use a
          simple for loop with a counter instead of the Set or List iteration.




          for (Integer i = accts.size()-1;  i>=0 ; i--) {
          Account a = accts[i];
          }





          share|improve this answer


























          • @AdrianLarson Thanks for suggestions. I should have looked more closely, I lifted off from the refered article. Fixed it now!

            – codeyinthecloud
            Jan 3 at 16:48






          • 1





            Thank you. I knew why I was getting the Exception and how to prevent it. I just wasn't sure if there was something wrong with my try-catch, if this was a Salesforce bug or as @AdrianLarson confirmed that all is good and it's the intended behavior.

            – shmuels
            Jan 3 at 18:34











          Your Answer








          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "459"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsalesforce.stackexchange.com%2fquestions%2f245359%2fexception-not-being-caught-system-finalexception-cannot-modify-a-collection-wh%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          2 Answers
          2






          active

          oldest

          votes








          2 Answers
          2






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          4














          Your exception is not being caught because FinalException is not catchable. Neither are LimitException nor AssertException.



          You can quickly check for yourself if a given type of exception is catchable using an anonymous script like the following:



          try
          {
          throw new FinalException();
          }
          catch (Exception pokemon)
          {
          system.debug('Cannot catch em all');
          }


          Note that in general:




          • you should know what specific types of exception you are expecting and catch only those

          • it is better to avoid the exception entirely if it is preventable, even if it can be caught






          share|improve this answer
























          • It's also very avoidable; just using a normal for loop instead of for-each fixes the problem.

            – sfdcfox
            Jan 3 at 16:29











          • Yeah I thought that might be a bit of a separate question though. Why can I not catch FinalException seems like one for which we might get plenty of dupes over the years.

            – Adrian Larson
            Jan 3 at 16:30











          • Yeah, I'm kind of surprised this is not a duplicate (but apparently not?). Good to have an answer like this available.

            – sfdcfox
            Jan 3 at 16:35











          • Thank you. For some reason the Docs only mention LimitException and AssertException but not FinalException.

            – shmuels
            Jan 3 at 18:31








          • 1





            It does not prove the difference between those two, but in general, if a standard exception is not caught with this script, you can assume it is by design.

            – Adrian Larson
            Jan 3 at 18:42
















          4














          Your exception is not being caught because FinalException is not catchable. Neither are LimitException nor AssertException.



          You can quickly check for yourself if a given type of exception is catchable using an anonymous script like the following:



          try
          {
          throw new FinalException();
          }
          catch (Exception pokemon)
          {
          system.debug('Cannot catch em all');
          }


          Note that in general:




          • you should know what specific types of exception you are expecting and catch only those

          • it is better to avoid the exception entirely if it is preventable, even if it can be caught






          share|improve this answer
























          • It's also very avoidable; just using a normal for loop instead of for-each fixes the problem.

            – sfdcfox
            Jan 3 at 16:29











          • Yeah I thought that might be a bit of a separate question though. Why can I not catch FinalException seems like one for which we might get plenty of dupes over the years.

            – Adrian Larson
            Jan 3 at 16:30











          • Yeah, I'm kind of surprised this is not a duplicate (but apparently not?). Good to have an answer like this available.

            – sfdcfox
            Jan 3 at 16:35











          • Thank you. For some reason the Docs only mention LimitException and AssertException but not FinalException.

            – shmuels
            Jan 3 at 18:31








          • 1





            It does not prove the difference between those two, but in general, if a standard exception is not caught with this script, you can assume it is by design.

            – Adrian Larson
            Jan 3 at 18:42














          4












          4








          4







          Your exception is not being caught because FinalException is not catchable. Neither are LimitException nor AssertException.



          You can quickly check for yourself if a given type of exception is catchable using an anonymous script like the following:



          try
          {
          throw new FinalException();
          }
          catch (Exception pokemon)
          {
          system.debug('Cannot catch em all');
          }


          Note that in general:




          • you should know what specific types of exception you are expecting and catch only those

          • it is better to avoid the exception entirely if it is preventable, even if it can be caught






          share|improve this answer













          Your exception is not being caught because FinalException is not catchable. Neither are LimitException nor AssertException.



          You can quickly check for yourself if a given type of exception is catchable using an anonymous script like the following:



          try
          {
          throw new FinalException();
          }
          catch (Exception pokemon)
          {
          system.debug('Cannot catch em all');
          }


          Note that in general:




          • you should know what specific types of exception you are expecting and catch only those

          • it is better to avoid the exception entirely if it is preventable, even if it can be caught







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Jan 3 at 16:25









          Adrian LarsonAdrian Larson

          105k19112237




          105k19112237













          • It's also very avoidable; just using a normal for loop instead of for-each fixes the problem.

            – sfdcfox
            Jan 3 at 16:29











          • Yeah I thought that might be a bit of a separate question though. Why can I not catch FinalException seems like one for which we might get plenty of dupes over the years.

            – Adrian Larson
            Jan 3 at 16:30











          • Yeah, I'm kind of surprised this is not a duplicate (but apparently not?). Good to have an answer like this available.

            – sfdcfox
            Jan 3 at 16:35











          • Thank you. For some reason the Docs only mention LimitException and AssertException but not FinalException.

            – shmuels
            Jan 3 at 18:31








          • 1





            It does not prove the difference between those two, but in general, if a standard exception is not caught with this script, you can assume it is by design.

            – Adrian Larson
            Jan 3 at 18:42



















          • It's also very avoidable; just using a normal for loop instead of for-each fixes the problem.

            – sfdcfox
            Jan 3 at 16:29











          • Yeah I thought that might be a bit of a separate question though. Why can I not catch FinalException seems like one for which we might get plenty of dupes over the years.

            – Adrian Larson
            Jan 3 at 16:30











          • Yeah, I'm kind of surprised this is not a duplicate (but apparently not?). Good to have an answer like this available.

            – sfdcfox
            Jan 3 at 16:35











          • Thank you. For some reason the Docs only mention LimitException and AssertException but not FinalException.

            – shmuels
            Jan 3 at 18:31








          • 1





            It does not prove the difference between those two, but in general, if a standard exception is not caught with this script, you can assume it is by design.

            – Adrian Larson
            Jan 3 at 18:42

















          It's also very avoidable; just using a normal for loop instead of for-each fixes the problem.

          – sfdcfox
          Jan 3 at 16:29





          It's also very avoidable; just using a normal for loop instead of for-each fixes the problem.

          – sfdcfox
          Jan 3 at 16:29













          Yeah I thought that might be a bit of a separate question though. Why can I not catch FinalException seems like one for which we might get plenty of dupes over the years.

          – Adrian Larson
          Jan 3 at 16:30





          Yeah I thought that might be a bit of a separate question though. Why can I not catch FinalException seems like one for which we might get plenty of dupes over the years.

          – Adrian Larson
          Jan 3 at 16:30













          Yeah, I'm kind of surprised this is not a duplicate (but apparently not?). Good to have an answer like this available.

          – sfdcfox
          Jan 3 at 16:35





          Yeah, I'm kind of surprised this is not a duplicate (but apparently not?). Good to have an answer like this available.

          – sfdcfox
          Jan 3 at 16:35













          Thank you. For some reason the Docs only mention LimitException and AssertException but not FinalException.

          – shmuels
          Jan 3 at 18:31







          Thank you. For some reason the Docs only mention LimitException and AssertException but not FinalException.

          – shmuels
          Jan 3 at 18:31






          1




          1





          It does not prove the difference between those two, but in general, if a standard exception is not caught with this script, you can assume it is by design.

          – Adrian Larson
          Jan 3 at 18:42





          It does not prove the difference between those two, but in general, if a standard exception is not caught with this script, you can assume it is by design.

          – Adrian Larson
          Jan 3 at 18:42













          2














          Answer from @Adrian is good, but on a different note the reason why you're getting this error was because your code attempts to modify a collection while it is being iterated in the for each loop, which is not allowed. Read about Read-only Collections




          If you need to modify the List or Set while iterating over it, use a
          simple for loop with a counter instead of the Set or List iteration.




          for (Integer i = accts.size()-1;  i>=0 ; i--) {
          Account a = accts[i];
          }





          share|improve this answer


























          • @AdrianLarson Thanks for suggestions. I should have looked more closely, I lifted off from the refered article. Fixed it now!

            – codeyinthecloud
            Jan 3 at 16:48






          • 1





            Thank you. I knew why I was getting the Exception and how to prevent it. I just wasn't sure if there was something wrong with my try-catch, if this was a Salesforce bug or as @AdrianLarson confirmed that all is good and it's the intended behavior.

            – shmuels
            Jan 3 at 18:34
















          2














          Answer from @Adrian is good, but on a different note the reason why you're getting this error was because your code attempts to modify a collection while it is being iterated in the for each loop, which is not allowed. Read about Read-only Collections




          If you need to modify the List or Set while iterating over it, use a
          simple for loop with a counter instead of the Set or List iteration.




          for (Integer i = accts.size()-1;  i>=0 ; i--) {
          Account a = accts[i];
          }





          share|improve this answer


























          • @AdrianLarson Thanks for suggestions. I should have looked more closely, I lifted off from the refered article. Fixed it now!

            – codeyinthecloud
            Jan 3 at 16:48






          • 1





            Thank you. I knew why I was getting the Exception and how to prevent it. I just wasn't sure if there was something wrong with my try-catch, if this was a Salesforce bug or as @AdrianLarson confirmed that all is good and it's the intended behavior.

            – shmuels
            Jan 3 at 18:34














          2












          2








          2







          Answer from @Adrian is good, but on a different note the reason why you're getting this error was because your code attempts to modify a collection while it is being iterated in the for each loop, which is not allowed. Read about Read-only Collections




          If you need to modify the List or Set while iterating over it, use a
          simple for loop with a counter instead of the Set or List iteration.




          for (Integer i = accts.size()-1;  i>=0 ; i--) {
          Account a = accts[i];
          }





          share|improve this answer















          Answer from @Adrian is good, but on a different note the reason why you're getting this error was because your code attempts to modify a collection while it is being iterated in the for each loop, which is not allowed. Read about Read-only Collections




          If you need to modify the List or Set while iterating over it, use a
          simple for loop with a counter instead of the Set or List iteration.




          for (Integer i = accts.size()-1;  i>=0 ; i--) {
          Account a = accts[i];
          }






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jan 3 at 16:47

























          answered Jan 3 at 16:31









          codeyinthecloudcodeyinthecloud

          3,4451426




          3,4451426













          • @AdrianLarson Thanks for suggestions. I should have looked more closely, I lifted off from the refered article. Fixed it now!

            – codeyinthecloud
            Jan 3 at 16:48






          • 1





            Thank you. I knew why I was getting the Exception and how to prevent it. I just wasn't sure if there was something wrong with my try-catch, if this was a Salesforce bug or as @AdrianLarson confirmed that all is good and it's the intended behavior.

            – shmuels
            Jan 3 at 18:34



















          • @AdrianLarson Thanks for suggestions. I should have looked more closely, I lifted off from the refered article. Fixed it now!

            – codeyinthecloud
            Jan 3 at 16:48






          • 1





            Thank you. I knew why I was getting the Exception and how to prevent it. I just wasn't sure if there was something wrong with my try-catch, if this was a Salesforce bug or as @AdrianLarson confirmed that all is good and it's the intended behavior.

            – shmuels
            Jan 3 at 18:34

















          @AdrianLarson Thanks for suggestions. I should have looked more closely, I lifted off from the refered article. Fixed it now!

          – codeyinthecloud
          Jan 3 at 16:48





          @AdrianLarson Thanks for suggestions. I should have looked more closely, I lifted off from the refered article. Fixed it now!

          – codeyinthecloud
          Jan 3 at 16:48




          1




          1





          Thank you. I knew why I was getting the Exception and how to prevent it. I just wasn't sure if there was something wrong with my try-catch, if this was a Salesforce bug or as @AdrianLarson confirmed that all is good and it's the intended behavior.

          – shmuels
          Jan 3 at 18:34





          Thank you. I knew why I was getting the Exception and how to prevent it. I just wasn't sure if there was something wrong with my try-catch, if this was a Salesforce bug or as @AdrianLarson confirmed that all is good and it's the intended behavior.

          – shmuels
          Jan 3 at 18:34


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Salesforce Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsalesforce.stackexchange.com%2fquestions%2f245359%2fexception-not-being-caught-system-finalexception-cannot-modify-a-collection-wh%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Human spaceflight

          Can not write log (Is /dev/pts mounted?) - openpty in Ubuntu-on-Windows?

          張江高科駅