While the names of the exceptions
UnsupportedOperationExceptionsound very similar, the Javadoc descriptions for each class indicate that they definitely have different intended uses.
The javax.naming.OperationNotSupportedException is a checked exception in the naming package that extends javax.naming.NamingException (which extends java.lang.Exception) and has been available since J2SE 1.3. As part of the
java.namingpackage, it is not surprising that this exception is specifically related to naming services. Specifically, as the description for this class states, this exception is intended for situations in which a particular naming Context implementation does not support the invoked method (operation).
For situations other than those described above for
OperationNotSupportedException, the better choice for a standard exception to indicate an unsupported method or operation is the
UnsupportedOperationExceptionis an unchecked exception in the java.lang package that (as an unchecked exception) extends java.lang.RuntimeException and has been available since J2SE 1.2.
As part of the more general
UnsupportedOperationExceptiondefinitely seems more general in nature than
javax.naming.OperationNotSupportedException. The description for this class states that this class is part of the Collections Framework.
The NetBeans IDE uses
UnsupportedOperationExceptionwhen it automatically implements methods for a newly created class implementing an interface. This is useful because it allows NetBeans to implement methods of defined in the interface so that the code will compile. At runtime, however, the unchecked exception
UnsupportedOperationExceptionwill be thrown when these methods are implemented. The
UnsupportedOperationExceptionallows the implementation class to be generated and compile, but does not hide the runtime issue of nothing actually being implemented in case a client calls that method.
The NetBeans example described above demonstrates a potentially appropriate use for
UnsupportedOperationException, but there are many situations in which its use is inappropriate. For the Collections Framework, there are valid reasons for its use, but in our own designs it can often be a "code smell" of design problems. As stated in Peter Williams's blog entry Why Java is Not My Favorite Language - Reason 16, it is sensible that any method that is important enough to be defined in an interface should generally be implemented in advertised implementations of that interface. This excerpt from Effective Java covers the primary use of
UnsupportedOperationException(an implementation does not implement a method in its interface that other implementations do implement).
A useful forum thread on
UnsupportedOperationExceptionis available at http://forum.java.sun.com/thread.jspa?threadID=633028&messageID=3665440. Another useful resource related to
UnsupportedOperationExceptionis the Java Collections API Design FAQ (see #1 and #2).