Introduction

In this article, we will understand UnsupportedOperationException in java, why does it occur and how to prevent it with examples.

Java UnsupportedOperationException
java.lang.UnsupportedOperationException is thrown when an operation is not supported by a particular object.
This exception can occur in many scenarios such as trying to add, remove or replace an element in an immutable collection.

It extends RuntimeException, which means that it is an unchecked exception, which is thrown at runtime. You cannot handle it at compile time with try-catch block.

Java docs for UnsupportedOperationException state,

Thrown to indicate that the requested operation is not supported.

UnsupportedOperationException in list
There are various ways to create a list. A list created using utility methods such as Arrays.asList() or List.of() return an unmodifiable list.
This means that operations that modify the size of this list are not permitted and if attempted, would throw UnsupportedOperationException. Example,

List<String> list = Arrays.asList("A", "B");
list.add("C");
System.out.println("Modified list:" + list);

This will result in

Exception in thread “main” java.lang.UnsupportedOperationException
at java.base/java.util.AbstractList.add(AbstractList.java:153)
at java.base/java.util.AbstractList.add(AbstractList.java:111)

Restricting operations
Suppose you have your own class and want to restrict a certain operation, then it can be done with UnsupportedOperationException, as below

public class User {
  private int id;

  private String name;

  public void setId(int id) {
    throw new UnsupportedOperationException(
          "You are not allowed to change user id");
  }

}

In this example, if someone tries to update user id, then it will restrict by throwing an UnsupportedOperationException.
Since, it is an unchecked exception, you do not need to declare it in the signature of setId().

Hope the article was useful.