Exceptions by Data Structures Java

Every concept of Java like Networking, IO Streams and Multithreading etc. comes with their bunch of exceptions. Similarly, Java Data Structures also have its own lot.

Name of Exception Conditions raised
IllegalStateException As the name indicates, this exception is thrown when the programmer is doing an operation that is illegal at the present moment (but legal at some other time or context). Iterator throws when remove() is called without calling next() method.
ConcurrentModificationException As the name indicates, this exception is thrown when two objects are modifying a DS. When Iterator is iterating the elements, the DS cannot add elements. Iterator is fail-fast.
UnsupportedOperationException . It is called when the method called is not supported by a data structure, For example, adding an element when the DS is read-only.
NullPointerException Raised when elements are added to a null DS object. Adding to reference variable of DS but not to object.
NoSuchElementException Retrieving an element that does not exist in the DS.

Just for example, ConcurrentModificationException is given as it looks very different from other. The above links in the table give all individual examples on exceptions.

import java.util.ArrayList;
import java.util.Iterator;

public class DSException
  public static void main(String args[])
    ArrayList states = new ArrayList();
    states.add("Telangana");  states.add("Andhra Pradesh");

    Iterator it = states.iterator();

Exceptions by Data Structures JavaOutput screen of Exceptions by Data Structures Java

Observe, while while loop iteration is going on with Iterator object, states is added an item. That is concurrently two objects are working on array list elements which leads trowing of ConcurrentModificationException.

Leave a Comment

Your email address will not be published. Required fields are marked *