Notes
Salesforce has introduced a significant change regarding the modification of collections, particularly sets, during iteration. Specifically, if you attempt to modify a set while iterating over it in a for
or foreach
loop, the platform will now throw a System.FinalException
. This behavior was different in API 61.0 and earlier versions, where such modifications were sometimes allowed, although they could lead to unexpected results.
Impacted Editions
This change applies universally to all Salesforce editions.
Example Scenario
Consider the following sample code that attempts to remove elements from a set while iterating over it:
Set<String> set_string = new Set<String>{'one', 'two', 'three'};
for (String str : set_string) {
System.debug(str);
set_string.remove(str);
System.debug(set_string.contains(str));
}
System.debug(set_string);
In this example, the code tries to remove elements from the set_string
during iteration. However, under API version 62.0 or later, this code will throw the following exception:
System.FinalException: Cannot modify a collection while it is being iterated.
Conclusion
This change enforces stricter rules to prevent potentially unsafe modifications during collection iteration, thereby reducing the likelihood of encountering unpredictable behavior in your Salesforce Apex code. Developers need to be aware of this change and adjust their code accordingly when working with loops and collections.