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 :)