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 2 hours ago

























      asked 2 hours ago









      shmuels

      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
            2 hours ago










          • 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
            2 hours ago










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










          • Thank you. For some reason the Docs only mention LimitException and AssertException but not FinalException.
            – shmuels
            19 mins ago












          • Yep makes sense. I was trying to find that link and include it but didn't have the time to do so. There may be more than just these three types which are not catchable, but I am not aware of any others at this time.
            – Adrian Larson
            15 mins ago



















          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
            2 hours ago






          • 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
            16 mins ago











          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
            2 hours ago










          • 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
            2 hours ago










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










          • Thank you. For some reason the Docs only mention LimitException and AssertException but not FinalException.
            – shmuels
            19 mins ago












          • Yep makes sense. I was trying to find that link and include it but didn't have the time to do so. There may be more than just these three types which are not catchable, but I am not aware of any others at this time.
            – Adrian Larson
            15 mins ago
















          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
            2 hours ago










          • 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
            2 hours ago










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










          • Thank you. For some reason the Docs only mention LimitException and AssertException but not FinalException.
            – shmuels
            19 mins ago












          • Yep makes sense. I was trying to find that link and include it but didn't have the time to do so. There may be more than just these three types which are not catchable, but I am not aware of any others at this time.
            – Adrian Larson
            15 mins ago














          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 2 hours ago









          Adrian Larson

          105k19112235




          105k19112235












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










          • 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
            2 hours ago










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










          • Thank you. For some reason the Docs only mention LimitException and AssertException but not FinalException.
            – shmuels
            19 mins ago












          • Yep makes sense. I was trying to find that link and include it but didn't have the time to do so. There may be more than just these three types which are not catchable, but I am not aware of any others at this time.
            – Adrian Larson
            15 mins ago


















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










          • 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
            2 hours ago










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










          • Thank you. For some reason the Docs only mention LimitException and AssertException but not FinalException.
            – shmuels
            19 mins ago












          • Yep makes sense. I was trying to find that link and include it but didn't have the time to do so. There may be more than just these three types which are not catchable, but I am not aware of any others at this time.
            – Adrian Larson
            15 mins ago
















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




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












          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
          2 hours ago




          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
          2 hours ago












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




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












          Thank you. For some reason the Docs only mention LimitException and AssertException but not FinalException.
          – shmuels
          19 mins ago






          Thank you. For some reason the Docs only mention LimitException and AssertException but not FinalException.
          – shmuels
          19 mins ago














          Yep makes sense. I was trying to find that link and include it but didn't have the time to do so. There may be more than just these three types which are not catchable, but I am not aware of any others at this time.
          – Adrian Larson
          15 mins ago




          Yep makes sense. I was trying to find that link and include it but didn't have the time to do so. There may be more than just these three types which are not catchable, but I am not aware of any others at this time.
          – Adrian Larson
          15 mins ago













          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
            2 hours ago






          • 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
            16 mins ago
















          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
            2 hours ago






          • 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
            16 mins ago














          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 2 hours ago

























          answered 2 hours ago









          codeyinthecloud

          3,2991423




          3,2991423












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






          • 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
            16 mins ago


















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






          • 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
            16 mins ago
















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




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




          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
          16 mins ago




          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
          16 mins ago


















          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.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • 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

          Eastern Orthodox Church

          Zagreb

          Understanding the information contained in the Deep Space Network XML data?