[jdom-interest] TODO clone [eg]

Dennis Sosnoski dms at sosnoski.com
Sat Apr 14 11:01:06 PDT 2001


I'd suggest that a better alternative for handling this is to continue to assume
clonability and throw an UnsupportedOperationException if a subclass wants to
prohibit cloning. The reason I suggest this is that attempting to clone a
non-clonable object will be a program structure error not normally recoverable by
alternate paths of execution; if someone wants to handle this specially they can
still catch the UnsupportedOperationException and do whatever they want with it.

Using checked exceptions for program errors is generally not a great idea, since it
adds complexity to the code without any real benefits. I'd suggest that
CloneNotSupportedException should have been a runtime exception in the first place,
but such a suggestion would contravene the Doctrine of Java Infallability (or is that
Gosling Infallability?). ;-)

  - Dennis

Joseph Bowbeer wrote:

> Things TODO related to Cloneable.
>
> 1. CloneNotSupportedException. Our clone implementations have the following
> form:
>
>     public Object clone() {
>         try {
>             return super.clone();
>         }
>         catch (CloneNotSupportedException ex) {
>             // Can't happen
>         }
>     }
>
> I suggest that clone *not* catch CloneNotSupportedException -- except in
> final classes.  Instead, add the exception to clone's declaration, as
> follows:
>
>     public Object clone() throws CloneNotSupportedException {
>         return super.clone();
>     }
>
> This gives the subclasses final say about whether they are cloneable or not,
> and it forces the programmer to deal with the possibility that a subclass
> may not be cloneable.
>
> If we don't add the exception to the declaration, we should at least throw
> an InternalError as a sanity check:
>
>     public Object clone() {
>         try {
>             return super.clone();
>         }
>         catch (CloneNotSupportedException ex) {
>             throw new InternalError();
>         }
>     }




More information about the jdom-interest mailing list