[jdom-interest] TODO clone [eg]

Ken Rune Helland kenh at csc.no
Tue Apr 17 05:45:37 PDT 2001

>In which case it's time for plan B:
> > > If we don't add the exception to the declaration, we
> > > should at least throw an InternalError as a sanity check
> > > in our own implementations:
> > >
> > >     public Object clone() {
> > >         try {
> > >             return super.clone();
> > >         }
> > >         catch (CloneNotSupportedException ex) {
> > >             throw new InternalError();
> > >         }
> > >     }
> > >

Since Element, Document and so on all implement the Clonable
interface super.clone(), wich is in effect Object.clone() since
all these classes are direct subclasses of Object, will never
throw CloneNotSuppotedException, so the catch clause can safely
be left empty.

If a subclass is not to be clonable it will have to throw an
exception in its own clone() implementation.

public Object clone()
   trow new SomeException();

and then Element.clone(), Document.clone() and so on will
never be called.

Since Element.clone(), Document.clone() and so on does not
declare "throws CloneNotSupportedException" no subclass of
these classes may throw this exception in the clone() metod.

So we have to options:

1. to add "throws CloneNotSupportedException" to the signature
of the clone() class thus saying its ok to create non-cloneable
subclasses and forcing all developers to catch this exception.

2. not to add this to the signature and say all subclasses shoud
be clonable. If some developer create non clonable subclasses they will
have to overide the clone() metod to throw some unchecked exception
for sanity checks and take care not to call clone() on these objects.

I prefere option 2 because
1. You dont get a lot of try catch blocks in the code.
2. If you develop a subclass that is not cloneable you obviusly
    dont need it to be cloned and so an unchecked exception for sanity
    checks shoud be ok.
3. Using option 1. woud break exsisting code as a lot of try/catch
    woud have to be added.


More information about the jdom-interest mailing list