Open In App

CloneNotSupportedException in Java with Examples

Last Updated : 24 Sep, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

CloneNotSupportedException is thrown to show that the clone method in class Object has been called to clone an object, but that the object’s class does not implement the Cloneable interface.

Hierarchy:

Those applications which override the clone method can also throw this type of exception to indicate that an object couldn’t or shouldn’t be cloned.

Syntax:

public class CloneNotSupportedException extends Exception

Example of CloneNotSupportedException :

Java




// Java program to demonstrate CloneNotSupportedException
 
class TeamPlayer {
 
    private String name;
 
    public TeamPlayer(String name)
    {
        super();
        this.name = name;
    }
 
    @Override public String toString()
    {
        return "TeamPlayer[Name= " + name + "]";
    }
 
    @Override
    protected Object clone()
        throws CloneNotSupportedException
    {
        return super.clone();
    }
}
 
public class CloneNotSupportedExceptionDemo {
 
    public static void main(String[] args)
    {
 
        // creating instance of class TeamPlayer
 
        TeamPlayer t1 = new TeamPlayer("Piyush");
        System.out.println(t1);
 
        // using try catch block
        try {
             
             // CloneNotSupportedException will be thrown
             // because TeamPlayer class not implemented
             // Cloneable interface.
              
            TeamPlayer t2 = (TeamPlayer)t1.clone();
            System.out.println(t2);
        }
 
        catch (CloneNotSupportedException a) {
            a.printStackTrace();
        }
    }
}


Output : 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads