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

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

最佳答案

抛出两个异常是什么意思?如果你抛出异常,方法就会停止。如果您需要组合消息,那么您可以执行以下操作:

//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/

相关文章:

java - 限制 POST 请求

java - 使用 Java Swing 高效重画线条

java - java编译器是否优化了无法访问的异​​常捕获分支?

java - Java 中抛出异常的高级概述

c++ - 构造函数可以在c++中调用另一个构造函数吗?

Java 访问数组中的值

java - 索引超出范围(文件读取)

ios - 错误 "Thread 1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)"是什么意思?

c++ - C++ 中的对象构建

c++ - c++构造函数中的段错误