Cloneable throws CloneNotSupportedException

Blrp picture Blrp · Jan 29, 2015 · Viewed 13k times · Source
public class test implements Cloneable {
    @Override
    public test clone() {
        return (test) super.clone();
    }

    public static void main(String[] args) {
        new test().clone();
    }
}

I get error: unreported exception CloneNotSupportedException when I try to compile this (at line 4, not the main). As far as I can tell, the entire purpose of implementing Cloneable is to get rid of the exception.

  • Is there a way to use super.clone() without throwing or catching the exception?
  • Does the interface actually do anything?

Answer

Marko Topolnik picture Marko Topolnik · Jan 29, 2015

Is there a way to use super.clone() without throwing or catching the exception?

No because Object#clone() (the method you are calling with super.clone()) declares it.

Does the interface actually do anything?

Yes, but very little: if you don't implement it, Object#clone() will actually throw the declared exception.