Understanding UnsupportedOperationException

前端 未结 3 1625
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-13 15:58

I don;t quite understand where I can throw this exception.

For instance, I\'m implementing the Future interface and don\'t want anyone calls t

相关标签:
3条回答
  • 2021-01-13 16:27

    Yes, you are right.

    The author of UnsupportedException is Joshua Bloch and as per his book and also from Collections design FAQ, if the object does not support an operation, the method can throw UnsupportedException.

    Caution should be taken before throwing this exception in your method because, it is of type RuntimeException/unchecked exception.

    Link to the book

    Author of the book and UnsupportedException class : Joshua Bloch

    /**
     * Thrown to indicate that the requested operation is not supported.<p>
     *
     * This class is a member of the
     * <a href="{@docRoot}/../technotes/guides/collections/index.html">
     * Java Collections Framework</a>.
     *
     * @author  Josh Bloch
     * @version %I%, %G%
     * @since   1.2
     */
    public class UnsupportedOperationException extends RuntimeException {
         ...
    }
    
    0 讨论(0)
  • 2021-01-13 16:29

    Technically UnsupportedOperationException is unchecked, and therefore can be thrown anywhere you like. However throwing it in unexpected places will cause your class to be less easy to use, and is not recommended.

    The place where UnsupportedOperationException is expected to be thrown is in "optional operations". 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.

    In your case timed "get" is pretty fundamental to the use of Future, and you will cause some surprise if you don't implement it. if you are going to do that, make sure it is well documented, and be aware that this will cause your implementation of Future to be unusable in some cases, and to potentially cause a program that uses it to crash.

    If you simply don't have the resources to write a timed get for your implementation of Future, consider using an implementation that already exists, such as extending your class from FutureTask.

    0 讨论(0)
  • 2021-01-13 16:43

    When you want that the callers of your method to know that the operation is not supported you can throw the UnsupportedOperationException.

    You can check here:

    This exception extends the RuntimeException class and thus, belongs to those exceptions that can be thrown during the operation of the Java Virtual Machine (JVM). It is an unchecked exception and thus, it does not need to be declared in a method’s or a constructor’s throws clause. Moreover, the UnsupportedOperationException exists since the 1.2 version of Java.

    0 讨论(0)
提交回复
热议问题