How to generate an UnsupportedOperationException in Java?

JavaObject Oriented ProgrammingProgramming

An UnsupportedOperationException is a subclass of RuntimException in Java and it can be thrown to indicate that the requested operation is not supported. The UnsupportedOperationException class is a member of the Java Collections Framework. This exception is thrown by almost all of the concrete collections like List, Queue, Set and Map.

Syntax

public class UnsupportedOperationException extends RuntimeException

Example

import java.util.*;
public class UnsupportedOperationExceptionTest {
   public static void main(String[] args) {
      List aList = new ArrayList();
      aList.add('a');
      aList.add('b');
      List newList = Collections.unmodifiableList(aList);
      newList.add('c');
   }
}

In the above example, it will generate an UnsupportedOperationException. In order to avoid this, we need to use the object of the collection rather than using the view object for modification.

Output

Exception in thread "main" java.lang.UnsupportedOperationException
  at java.util.Collections$UnmodifiableCollection.add(Collections.java:1055)
     at UnsupportedOperationExceptionTest.main(UnsupportedOperationExceptionTest.java:9)
raja
Updated on 03-Jul-2020 07:45:55

Advertisements