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