0

I was wondering how can I execute both of these exceptions in the same constructor. My program compiles fine, but it won't throw the exception for the second if statement.

public Segment(Point firstPoint, Point secondPoint) {
    if(firstPoint == null || secondPoint == null)
        throw new IllegalArgumentException("Cannot pass a null value");
    if(firstPoint == secondPoint)
        throw new IllegalArgumentException("Segment cannot be 0");

    this.endPoint1 =  new Point(firstPoint);
    this.endPoint2 =  new Point(secondPoint);
}
buræquete
  • 14,226
  • 4
  • 44
  • 89
  • You can't. One exception max. – user2357112 Sep 30 '17 at 04:29
  • learn to put `{}` around ALL `if/elseif/else` statements! If either of the points is `null` it will never get to that line. There is nothing wrong with this code. –  Sep 30 '17 at 04:30
  • 1
    Also, `firstPoint == secondPoint` is a reference equality comparison, not a test of whether the two objects represent the same position. – user2357112 Sep 30 '17 at 04:34

1 Answers1

1

What do you mean by throwing two exceptions? If you make throw, than method stops. If you need to combine messages, so you can do something like this:

//Parameterized constructor
public Segment(Point firstPoint, Point secondPoint)
{
    String error = "";
    if(firstPoint == null || secondPoint == null) {
        error  = "Cannot pass a null value";
    }
    if(firstPoint == secondPoint) {
        error = error.equals("") ?
                "Segment cannot be 0" :
                error + ". Segment cannot be 0"
    }

    if (!error.equals("")){
        throw new IllegalArgumentException("Segment cannot be 0");
    }

    this.endPoint1 =  new Point(firstPoint);
    this.endPoint2 =  new Point(secondPoint);
}
Ilya G.
  • 61
  • 7