An unaccepted, unwanted event that disturbed the normal flow of a program is called an Exception. Most of the time exception is caused by our program and these are recoverable. Example: If our program requirement is to read data from the remote file locating in the U.S.A. At runtime, if a remote file is not available then we will get RuntimeException saying FileNotFoundException. If FileNotFoundException occurs we can provide the local file to the program to read and continue the rest of the program normally.
There are mainly two types of exception in java as follows:
- Checked Exceptions are the exceptions that are checked by the compiler for the smooth execution of the program at runtime is called a checked exception. In our program, if there is a chance of rising checked exceptions then compulsory we should handle that checked exception (either by try-catch or throws keyword) otherwise we will get a compile-time error.
- Unchecked Exceptions are the exceptions that are not checked by the compiler, whether programmer handling or not such types of exceptions are called unchecked exceptions. Examples of unchecked Exceptions are ArithmeticException, ArrayStoreException, etc.
Note: Whether the exception is checked or unchecked every exception occurs at run time only if there is no chance of occurring any exception at compile time.
ConcurrentModificationException is the child class of RuntimeException and hence it is an unchecked exception. This exception is rise when an object is tried to be modified concurrently when it is not permissible i.e when one thread is iterating over some collection class object and if some other thread tried to modify or try to make some changes on that collection object then we will get ConcurrentModificationException. This exception usually occurs when we are working with Java collections classes.
The above program is a single-threaded program and here we can avoid ConcurrentModificationException by using iterator’s remove( ) function, we can remove an object from an underlying collection object without getting any exception.
List Value Before Iteration:[1, 2, 3, 4, 5] List Value After iteration:[1, 2, 4, 5]
Note: In multi-threaded program we can avoid ConcurrentModificaionException by using ConcurrentHashMap and CopyOnWriteArrayList classes. These classes help us in avoiding ConcurrentModificaionException.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.