How to throw an IllegalArgumentException when an array is null or empty?

    /**
     * This constructor accepts an array of points as input. Copy the points into the array points[]. 
     * 
     * @param  pts  input array of points 
     * @throws IllegalArgumentException if pts == null or pts.length == 0.
     */
    protected AbstractSorter(Point[] pts) throws IllegalArgumentException
    {
        try{
            for(int i = 0; i < pts.length; i++)
            {
                points[i] = pts[i];
            }
        }
        catch()
        {

        }
    }

I know this should be really simple, but how would I throw this exception with those conditions?

Answer

Your code should be like this,

protected AbstractSorter(Point[] pts) throws IllegalArgumentException
{
    if(pts == null || pts.length == 0 ){
      throw new IllegalArgumentException();
    }
    for(int i = 0; i < pts.length; i++)
    {
        points[i] = pts[i];
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *