William the Coderer
William the Coderer

Reputation: 708

Java: Alternative to handling a strange error/return type with exceptions

I have a function as part of a rectangle class (points inside it are immutable doubles, so the rectangle is also immutable), and I need to provide a method for calculating intersections with another rectangle. The method will return the calculated intersection rectangle. However, if the objects do not intersect at all, it throws an exception.

The only alternative to throwing an exception I could think of would be to return a special type called RectIntersection, and the caller could poll that object to see if the intersection calculation failed or not. I like this better than throwing an exception, but it leaves me needing to test every call to this function to check the newly created object.

Any other suggestions for handling this condition?

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

Upvotes: 0

Views: 274

Answers (1)

Robert
Robert

Reputation: 6540

Why not just return null? You just check to make sure the return value isn't null before using it.

Or, as Oli noted, return an empty rectangle. Arguably, that's what the intersection of two nonoverlapping rectangles is anyway. You may not even need to modify the code that uses it (it's easy to forsee code that does nothing given an empty rect), or you can add an isEmpty method to check the result. There's precdent for this, in the Rectangle class

You're right, exceptions aren't really the tool to use for nonexceptional conditions.

Upvotes: 2

Related Questions