我想知道如何在同一个构造函数中执行这两个异常。我的程序编译得很好,但它不会抛出第二个 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);
}
最佳答案
抛出两个异常是什么意思?如果你抛出异常,方法就会停止。如果您需要组合消息,那么您可以执行以下操作:
//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);
}
关于java - 如何在一个构造函数中抛出多个异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46499569/