[Solved] Exception UnsupportedOperationException Example

java.lang.UnsupportedOperationException is RuntimeException and Unchecked Exception which expected to thrown by JVM(Java Virtual Machine) when try to perform an “optional operation” which is not allowed an object .

The Java framework contains plenty of these, especially in the Collections framework. For example “add” is an optional operation, because immutable collections should not allow it. Throwing UnsupportedOperationException is exactly what you should do if you don’t want to write one of these methods.

Constructors :

  • UnsupportedOprationException() : Constructs an UnsupportedOperationException with no detail message.
  • UnsupportedOprationException(String message) : Constructs an UnsupportedOperationException with specified detail message.
  • UnsupportedOprationException(String message, Throwable cause) : Constructs an UnsupportedOperationException with specified detail message and cause.
  • UnsupportedOprationException(Throwable cause) : Constructs a new exception with the  specified cause and a detail message of (cause==null ? null : cause.toString()) (which typically contains the class and detail message of cause).

Example :

In below example problem is List returned from Arrays.AsList() is not like java.util.ArrayList. Arrays.asList() returns a java.util.Arrays$ArrayList which is an immutable list. You can not add or remove any element from this list otherwise will get java.lang.UnsupportedOperationException Exception.

package exceptionhandeling;

import java.util.Arrays;
import java.util.List;

public class UnsupportedOperationException {

	public static void main(String[] args) {
		String [] empArr={"Saurabh","Gaurav","Shailesh","Ankur","Ranjith","Ramesh"};
		//Convert Array to LIst
		List empList=Arrays.asList(empArr);
		/**
		 * By the time you get to the remove(i) statement, list is no longer a java.util.ArrayList.
		 * When you call Arrays.asList it does not return a java.util.ArrayList. It returns a java.util.Arrays$ArrayList which is an immutable list. You cannot add to it and you cannot remove from it.

		 * Not every List implementation support add method because Arrays.asList() returned
		 * immutable list of fixed size
		 */
		for(String emp:empList)
		{
			empList.add("Sachin");
			System.out.println(emp);
		}

	}

}

Output:

Exception in thread "main" java.lang.UnsupportedOperationException
	at java.util.AbstractList.add(Unknown Source)
	at java.util.AbstractList.add(Unknown Source)
	at example.UnsupportedOperationExceptionExample.main(UnsupportedOperationExceptionExample.java:21)

Advertisements

This site uses Akismet to reduce spam. Learn how your comment data is processed.