tags:

views:

115

answers:

2

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?

+5  A: 

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...

Jon Skeet
How the heck did you answer this question so fast? Sheesh, I'm beginning to believe the "Jon Skeet facts" :)
MetroidFan2002
I'd use `throw new Error(exc);`, if someone forced me at knife point to use `Object.clone`.
Tom Hawtin - tackline
5 minutes between question and answer, 72 words in the answer. If the question was spotted inside a minute or two and the the answer requires no research it is reasonable to expect a computer professional to be able to type at 18-24 wpm
Rich Seller
A: 
Rodrigo Asensio