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

























      asked 11 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
            11 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
            11 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
            11 hours ago










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








          • 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
            9 hours 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
            11 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
            9 hours 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
            11 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
            11 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
            11 hours ago










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








          • 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
            9 hours 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
            11 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
            11 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
            11 hours ago










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








          • 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
            9 hours 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 11 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
            11 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
            11 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
            11 hours ago










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








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


















          • It's also very avoidable; just using a normal for loop instead of for-each fixes the problem.
            – sfdcfox
            11 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
            11 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
            11 hours ago










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








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
















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




          It's also very avoidable; just using a normal for loop instead of for-each fixes the problem.
          – sfdcfox
          11 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
          11 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
          11 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
          11 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
          11 hours ago












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






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






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




          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
          9 hours 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
            11 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
            9 hours 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
            11 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
            9 hours 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 11 hours ago

























          answered 11 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
            11 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
            9 hours ago


















          • @AdrianLarson Thanks for suggestions. I should have looked more closely, I lifted off from the refered article. Fixed it now!
            – codeyinthecloud
            11 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
            9 hours ago
















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




          @AdrianLarson Thanks for suggestions. I should have looked more closely, I lifted off from the refered article. Fixed it now!
          – codeyinthecloud
          11 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
          9 hours 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
          9 hours 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

          CARDNET

          Boot-repair Failure: Unable to locate package grub-common:i386

          濃尾地震