Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/398.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 构造函数应抛出IllegalArgumentException(在此()之前需要检查)_Java_Exception_Constructor - Fatal编程技术网

Java 构造函数应抛出IllegalArgumentException(在此()之前需要检查)

Java 构造函数应抛出IllegalArgumentException(在此()之前需要检查),java,exception,constructor,Java,Exception,Constructor,我希望我的构造函数在使用错误参数调用时抛出一个带有自写错误消息的IllegalArgumentException public Card(int top, int left, int right) { this(TOP.get(top) + 3 * LEFT.get(left) + 9 * RIGHT.get(right)); } 错误的参数意味着TOP.get(TOP)(resp.LEFT,RIGHT)为空,因为Map不包含这样的元素。问题是我不能先测试它,因为this()以前不允许

我希望我的构造函数在使用错误参数调用时抛出一个带有自写错误消息的
IllegalArgumentException

public Card(int top, int left, int right) {
    this(TOP.get(top) + 3 * LEFT.get(left) + 9 * RIGHT.get(right));
}

错误的参数意味着
TOP.get(TOP)
(resp.LEFT,RIGHT)为空,因为
Map
不包含这样的元素。问题是我不能先测试它,因为
this()
以前不允许使用代码。

添加一个帮助器方法,为您检查输入:

public Card(int top, int left, int right) {
    this(helper(top, left, right));
}

private static int helper(int top, int left, int right) {
    if (TOP.get(top) == null || LEFT.get(left) == null || RIGHT.get(right) == null)) {  
        throw new IllegalArgumentException();
    }
    return TOP.get(top) + 3 * LEFT.get(left) + 9 * RIGHT.get(right);
}

添加用于检查输入的帮助器方法:

public Card(int top, int left, int right) {
    this(helper(top, left, right));
}

private static int helper(int top, int left, int right) {
    if (TOP.get(top) == null || LEFT.get(left) == null || RIGHT.get(right) == null)) {  
        throw new IllegalArgumentException();
    }
    return TOP.get(top) + 3 * LEFT.get(left) + 9 * RIGHT.get(right);
}