如何在一个构造函数中抛出多个异常?

时间:2017-09-30 04:27:29

标签: java exception constructor

我想知道如何在同一个构造函数中执行这两个异常。我的程序编译得很好,但它不会抛出第二个if语句的异常。

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);
}

1 个答案:

答案 0 :(得分:1)

抛出两个例外是什么意思?如果你进行投掷,则方法停止。如果您需要组合消息,那么您可以执行以下操作:

//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);
}