I'm going through some old code and found the following:
public class MyClass implements Cloneable {
public Object clone() {
Object o = null;
try {
o = super.clone();
} catch (CloneNotSupportedException ex) {
}
return o;
}
}
I've read the javadocs on Object.clone(), and I'm trying to figure out why this catch is even there. I mean, I understand it has to be there because Object.clone() throws it, but when would it ever get there, if I'm only extending Object by default, and this class is implmenting Cloneable? If this class was extended and the sub-class didn't implement Cloneable, is that what it's there for?
So is it OK to leave that catch block empty?
To avoid the CloneNotSupportedException , the Cloneable interface should be implemented by the class whose objects need to be cloned. This indicates to the Object. clone() method that it is legal to create a clone of that class and helps avoid the CloneNotSupportedException .
A class must implement the Cloneable interface if we want to create the clone of the class object. The clone() method of the Object class is used to create the clone of the object. However, if the class doesn't support the cloneable interface, then the clone() method generates the CloneNotSupportedException.
Creating a copy using the clone() methodclone() to obtain the cloned object reference. The class must also implement java. lang. Cloneable interface whose object clone we want to create otherwise it will throw CloneNotSupportedException when clone method is called on that class's object.
If a developer attempts to Clone an object which does not implement the Cloneable interface, it will throw an exception called CloneNotSupportedException.
No, don't leave it empty. Log and throw a RuntimeException
. Always do this for things that you think are impossible - that way, if the impossible eventually happens, it's treated as an unexpected error (which it is) rather than just returning null
as if nothing bad had happened.
Admittedly I really don't expect you to ever see it, but the above is a generally good way to handle errors you shouldn't see...
there is no problem if you re-throw or not the exception. Your object MyClass will never throw CloneNotSupportedEx because it is being thrown only when the interface is not implemented. See the javadoc for Clonable
By convention, classes that implement this interface should override Object.clone (which is protected) with a public method. See {@link java.lang.Object#clone()} for details on overriding this method.
Note that this interface does not contain the clone method. Therefore, it is not possible to clone an object merely by virtue of the fact that it implements this interface. Even if the clone method is invoked reflectively, there is no guarantee that it will succeed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With