I am trying to handle the java ConcurrentModificationException exception using try-catch block but still I am getting the same error when compiling the code.
import java.util.*;
public class failFast{
public static void main(String[] args){
Map<Integer,String> map = new HashMap<>();
map.put(100,"Melani");
map.put(101,"Harshika");
map.put(102,"Nimna");
Iterator itr = map.keySet().iterator();
while(itr.hasNext()){
System.out.println(itr.next());
try{
map.put(103,"Nirmani");
}
catch(Exception e){
System.out.println("Exception is thrown "+e);
}
}
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextNode(Unknown Source)
at java.util.HashMap$KeyIterator.next(Unknown Source)
at failFast.main(failFast.java:12)
I don't now exactly what you are trying to achive (your code doesn't make much sense for me). Basically you can't change a
Map
or an otherCollection
while iterating over it. The only way to change the underlying structure is with the actualIterator
but this is very limited. To catch theConcurrentModificationException
makes not much sense because with your code it will always be thrown, so the catch-block would be your normal code flow, which is really not good.Possibility 1: Copy
keySet
to an other collection and iterate over this onePossibility 2: Collect all the changes and apply them after the loop (this is what I would do)