How to generate an UnsupportedOperationException in Java?


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)

Updated on: 03-Jul-2020

366 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements