Rohith R
Rohith R

Reputation: 1329

Implementing a clone function

I have a class named Garage :

class Garage extends Vehicle implements Cloneable
{
    Vehicle[] v= new Vehicle [10];

    public Garage ()
    {
        for (int i=0;i<10;i++)
            this.v[i]=new Vehicle ();
    }

    public Garage clone () throws CloneNotSupportedException
    {
        try 
        {
            return (Garage) super.clone ();
        }
        catch (CloneNotSupportedException e)
        {
            return null;    
        }
    }

public static void main (String[] args)
{
    Garage g1,g2;
    g1=new Garage ();

    for (int i=0;i<10;i++)
        g1.v[i].setVehicleAttr (i,i,i,Integer.toString(i));

    g2=new Garage ();
    g2 = g1.clone ();
}
};

When I compile it.. It give The Following Error... Even Though i have handled the exception it says exception must be caught...Why is this happening....?

Garage.java:32: error: unreported exception CloneNotSupportedException; must be caught or declared to be thrown g2 = g1.clone ();

Upvotes: 1

Views: 650

Answers (1)

no you haven't: g2 = g1.clone (); is not in a try/catch block for the exception that the clone() method you're written is supposed to throw.

Even if you catch the throw inside the method (which you should not do), your signature still tells java that the method will throw under unknown conditions, and thus code that calls it must use a try/catch, or the method inside which the call is made must itself have a throw CloneNotSupportedException.

Either try/catch inside the method and don't declare a throw, or do declare a throw and then let the calling code handle the try/catch.

Upvotes: 2

Related Questions