0
    /**
     * 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?

kaya3
  • 47,440
  • 4
  • 68
  • 97

3 Answers3

2
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];
        }
}
nylanderDev
  • 531
  • 4
  • 14
Dinesh
  • 1,046
  • 1
  • 8
  • 17
  • 1
    This isn't valid Java code because the `catch` block doesn't declare a variable for the exception to be caught. But more importantly there shouldn't be a `try` or `catch` block at all. – kaya3 Mar 07 '20 at 19:00
1

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];
    }
}
Anurodh Singh
  • 814
  • 5
  • 9
0
/**
     * 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
    {
        if(pts == null || pts.length == 0)
            throw new IllegalArgumentException();
        else{
            for(int i = 0; i < pts.length; i++)
                points[i] = pts[i];
        }
    }

This is what I have come up with, with your advice.

  • Nice one, yes, this is a correct solution. One thing I'll suggest is always use braces `{` ... `}` even for the `if` and `for` blocks here where there is only one statement inside them; it makes your code more readable, and makes it easier to edit without introducing bugs. – kaya3 Mar 07 '20 at 19:06
  • "else" is unnecessary after throw. Also it is unusual to answer your own question if there is a similar answer by someone else, and duplicate answers have little value. – tkruse Mar 08 '20 at 02:03