【发布时间】:2013-06-05 15:22:12
【问题描述】:
我正在编写代码来查找和交叉 2 行。 当线的斜率相等时,它们不相交。但另一方面,具有相等斜率的输入是完全有效的。
public static Point calculateIntersection(Line line1, Line line2) {
if (line1 == null || line2 == null) {
throw new NullPointerException(" some message ");
}
if (line1.getConstant() == line2.getConstant()) {
return new Point(0, line1.getConstant());
}
if (line1.getSlope() == line2.getSlope()) {
throw new IllegalArgumentException("slopes are same, the lines do not intersect.");
}
int x = (line2.getConstant() - line1.getConstant()) / (line1.getSlope() - line2.getSlope());
int y = line1.getSlope() * x + line1.getConstant();
return new Point(x, y);
}
问题是抛出非法参数异常是正确的做法吗? 由于输入是有效的,它并不能完全说服我。
自定义异常是正确的做法吗? 听起来是个不错的选择,但额外的意见会有所帮助。
谢谢
【问题讨论】:
-
这真的是个例外吗?我完全赞成使用异常而不是可为空的返回值,但在这种情况下,它会表达一个预期的返回值。
-
输入不匹配异常,数字格式异常或者在最一般的情况下,只需添加非法参数异常。