1

I am having trouble with passing tests for my IllegalArgumentException. When no object is passed into my method, the IllegalArgumentException will not happen.

public double distanceTo(Point otherPoint) {
    int x = (otherPoint.x - this.x);
    int y = (otherPoint.y - this.y);
    double xDbl = Math.pow(x, 2);
    double yDbl = Math.pow(y, 2);
    if (otherPoint!=null) {
        return Math.hypot(xDbl,yDbl);
    } else {
        throw new IllegalArgumentException("No value for otherPoint object");
    }
}

1 Answers1

1

Since you're accessing properties x, y of otherPoint at the beginning of the function, if otherPoint is null, it will throw the NullPointerException instead of IllegalArgumentException. In order to throw the IllegalArgumentException when otherPoint is null, you need to bring your null check in the if statement to the beginning of the function, before accessing the properties x and y

public double distanceTo(Point otherPoint) {
    if (otherPoint==null) {
        throw new IllegalArgumentException("No value for otherPoint object");
    }
    int x = (otherPoint.x - this.x);
    int y = (otherPoint.y - this.y);
    double xDbl = Math.pow(x, 2);
    double yDbl = Math.pow(y, 2);
    return Math.hypot(xDbl,yDbl); 
}
VietHTran
  • 2,175
  • 2
  • 8
  • 16
  • 1
    This makes so much sense! Stupid overlook on my part. Order! Order! Order! Thank you. I have some other errors now, but unrelated. I'll work on those now. Again, thank you. – basketstheclown Oct 04 '20 at 04:31