Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

UnsupportedOperationException — unsupported operation

UnsupportedOperationException means that the requested operation is not supported. It commonly occurs when attempting to modify an unmodifiable list, such as one created with List.of(...). The solution is to choose an object that supports the required operation, not merely catch the exception.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

throw new UnsupportedOperationException("Operation not supported");

UnsupportedOperationException in java.lang signals that the requested operation is not supported. It extends RuntimeException: it is unchecked, so the compiler does not require catching it or declaring it in throws.

A typical case is calling add on a list created with List.of(...). That list is unmodifiable: adding, removing, and replacing elements throws this exception. An unmodifiable list does not, however, imply that its elements are themselves immutable.

When diagnosing the problem, inspect the stack trace, the method contract, and how the object was created. The type List alone does not guarantee support for modification. If changes are required, choose an implementation whose contract permits them; do not ignore the exception as a fix.

In your own API, throw this exception when an operation is unsupported under the contract. Available constructors are UnsupportedOperationException(), UnsupportedOperationException(String message), UnsupportedOperationException(Throwable cause), and UnsupportedOperationException(String message, Throwable cause). In the last form, the cause's message is not automatically included in the exception's message.

Examples

import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> names = List.of("Ada", "Linus");
        try {
            names.add("Grace");
        } catch (UnsupportedOperationException e) {
            System.out.println("UnsupportedOperationException");
        }
        System.out.println(names);
    }
}

Result

UnsupportedOperationException
[Ada, Linus]

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources