JAVA

Exceptions

Date Published:
Last Modified:

Checked Exceptions

Any exception that is a subclass of Exception (or Exception itself), except for RuntimeException and it’s subclasses, is a checked exception.

The Java compiler forces you to catch checked exceptions (and either swallow or re-throw).

Some common examples of checked exceptions are:

  • IOException
  • FileNotFoundException
  • ClassNotFoundException
  • InvocationTargetException
  • SQLException
  • DataAccessException 

ConcurrentModificationException

The exception can be thrown while trying to remove an element from a Collection (e.g. an ArrayList) while iterating over it using a standard for loop.

Another way a ConcurrentModificationException can be thrown is if you forget to copy a Collection and rather take a reference to it, and then try and access the Collection.

For example, the following line won’t actually copy the entire list:

// This does not actually copy the list
ArrayList<Integer> newList = oldList.subList(0, 5);
oldList.get(2); // This will throw a ConcurrentModificationException

// Perform a deep copy of the list
ArrayList<Integer> newListSafe = new ArrayList<>(oldList.subList(0, 5));
oldList.get(2); // This is o.k., since newListSafe is a deep copy of the list

Like this page? Upvote with shurikens!

Tags:

    comments powered by Disqus