Starting from API version 62.0, modifying elements of a set while iterating the set in a for or foreach() loop throws an exception: System.FinalException: Cannot modify a collection while it is being iterated. In the previous API versions, modifications to sets while iterating were sometimes allowed and generated unexpected results
Example: Below code removes elements while iterating the set, which throws an exception: System.FinalException
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);
