Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Clone method - how do I throw the exception?

807600Nov 13 2007 — edited Nov 14 2007
Yesterday I was having some problems with grasping the cloneable interface and writing the method. Well I think that I've sorted it out but I'm not exactly sure. I don't know how I'm supposed to throw the exception.

When attempting to clone an object in my test method, I recieve an error saying unreported exception CloneNotSupportedException, must be caught or declared to be thrown.

Here is my Cloneable interface:-
public interface Cloneable {
    
    Object clone() throws CloneNotSupportedException;
    
}
Here is my method for cloning an object below:-
    public Object clone() throws CloneNotSupportedException
    {
    try {
        this.clone();
        }
    catch (CloneNotSupportedException e)
        {
        System.out.println("Caught CloneNotSupportedException " + e.getMessage());
        }
        return this;        
    }
Here is my call to the method in my main class (*this is where the error is*):-
        Object card21 = card20.clone();
I have been through the trail on handling exceptions, but I still don't unserstand what I am doing wrong. Also, if I wanted to clone a Card object (from Card class), shouldn't my method for cloning be as below instead?
    public Card clone() throws CloneNotSupportedException
    {
    try {
        this.clone();
        }
    catch (CloneNotSupportedException e)
        {
        System.out.println("Caught CloneNotSupportedException " + e.getMessage());
        }
        return this;        
    }
Then when trying to clone a card object it should be like this in my main method:-
Card card2 = card1.clone();
Would appreciate any help thanks :)
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Dec 12 2007
Added on Nov 13 2007
18 comments
2,025 views