Java:替代处理带有异常的奇怪错误/返回类型

时间:2011-11-11 01:19:08

标签: java exception-handling error-handling

我有一个函数作为矩形类的一部分(其中的点是不可变的双精度,因此矩形也是不可变的),我需要提供一种计算与另一个矩形的交点的方法。该方法将返回计算的交叉矩形。但是,如果对象根本不相交,则会抛出异常。

抛出一个我能想到的异常的唯一替代方法是返回一个名为RectIntersection的特殊类型,调用者可以轮询该对象以查看交集计算是否失败。我比抛出一个异常更喜欢这个,但它让我需要测试每次调用这个函数来检查新创建的对象。

处理此情况的其他任何建议?

static public DoubleRect calcRectIntersection(DoubleRect r1, DoubleRect r2) throws DoubleRectException {

    if((r1.topLeft.x > r2.bottomRight.x || r1.bottomRight.x < r2.topLeft.x || r1.topLeft.y > r2.bottomRight.y || r1.bottomRight.y < r2.topLeft.y) != true)
    {
        return new DoubleRect(r1.topLeft.x >= r2.topLeft.x ? r1.topLeft.x : r2.topLeft.x,
                r1.topLeft.y >= r2.topLeft.y ? r1.topLeft.y : r2.topLeft.y,
                r1.bottomRight.x <= r2.bottomRight.x ? r1.bottomRight.x : r2.bottomRight.x,
                r1.bottomRight.y <= r2.bottomRight.y ? r1.bottomRight.y : r2.bottomRight.y);
    }
    else throw new DoubleRectException("Call to calcRectIntersection() could not complete since the two rectangles did not intersect");
}

1 个答案:

答案 0 :(得分:2)

为什么不返回null?您只需检查以确保返回值在使用前不为null。

或者,正如Oli所说,返回一个空矩形。可以说,无论如何,这就是两个非重叠矩形的交集。您甚至可能不需要修改使用它的代码(很容易预见到没有空矩形的代码),或者您可以添加一个isEmpty方法来检查结果。在Rectangle class

中有预见性

你说得对,异常并不是用于非常规条件的工具。