Explain Codes LogoExplain Codes Logo

What is the standard exception to throw in Java for not supported/implemented operations?

java
exception-handling
best-practices
java-exceptions
Anton ShumikhinbyAnton Shumikhin·Oct 4, 2024
TLDR

Throw a UnsupportedOperationException when signaling unimplemented features in Java:

//Surprise! This feature is still inside Thought Incubator Co. throw new UnsupportedOperationException("Not implemented");

In other words, when a specific functionality that's yet to be implemented is called upon, UnsupportedOperationException plays your well-wisher by providing an explicit cry out about the under-construction method.

Deep dive: Unimplemented operations and exception throwing

Picking the right exception: UnsupportedOperationException

Java's abundance of exceptions might confuse programmers when it comes to deciding which is the most appropriate to throw. However, for indicating methods that are unsupported or unimplemented, using UnsupportedOperationException maintains code cohesion and simplicity.

The NotImplementedException dilemma

The Apache Commons Lang library provides a NotImplementedException, but remember Sherlock's advice - don't introduce new variables when not needed. This additional dependency, while detailed and precise, might be overdoing it. Be aware that NotImplementedException was playing hide and seek between versions 2.6 and 3.2 of the Apache Commons Lang library.

The power of meaningful messages

A movie without subtitles might be frustrating to some viewers. Similarly, throwing an UnsupportedOperationException without a message can lead to confusion. Always provide a relevant description:

//Sorry, 'this.sort()' doesn't work on things that don't like change. Maybe try Zen meditation? throw new UnsupportedOperationException("Sort operation is not supported on an unmodifiable list");

Elements to consider when throwing exceptions

Coherency with standard exceptions

In Java, always lean towards sticking to the standard exceptions like UnsupportedOperationException. It eliminates ambiguity and aligns your code with fellow Java developers' expectations.

Auto-generated IDE exceptions

Some IDEs including NetBeans, jubilantly throw UnsupportedOperationException in their auto-generated method stubs. They expect you to revisit these and finish the implementation before deployment.

Considering custom exceptions

Creating a custom exception could be viable when you want to include more contextual data or have particular error handling strategies. But remember, with great power, comes great responsibility! A specialized exception also introduces more complexity to your error handling ecosystem.