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");
    }
}
  • For the check to do any good it needs to occur before you actually use the argument. This looks like the first line of the method will cause an NPE if otherPoint is null. – Nathan Hughes Oct 04 '20 at 04:25
  • I'll be honest, I did try that before. I had the if statement switched to have the condition be (otherPoint==null). I just tried that again and still can't seem to get it to work. – basketstheclown Oct 04 '20 at 04:29

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,233
  • 2
  • 9
  • 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