TheAlgorithms/Java · error · IllegalArgumentException

Height must be greater than 0

Error message

Height must be greater than 0

What it means

Thrown by Area.surfaceAreaCuboid when the 'height' argument is <= 0. This is the final guard in the cuboid method; reaching it means length and width were both valid, so the failure is specifically the height.

Source

Thrown at src/main/java/com/thealgorithms/maths/Area.java:54

    }

    /**
     * Calculate the surface area of a cuboid.
     *
     * @param length length of the cuboid
     * @param width width of the cuboid
     * @param height height of the cuboid
     * @return surface area of given cuboid
     */
    public static double surfaceAreaCuboid(final double length, double width, double height) {
        if (length <= 0) {
            throw new IllegalArgumentException("Length must be greater than 0");
        }
        if (width <= 0) {
            throw new IllegalArgumentException("Width must be greater than 0");
        }
        if (height <= 0) {
            throw new IllegalArgumentException("Height must be greater than 0");
        }
        return 2 * (length * width + length * height + width * height);
    }

    /**
     * Calculate the surface area of a sphere.
     *
     * @param radius radius of sphere
     * @return surface area of given sphere
     */
    public static double surfaceAreaSphere(final double radius) {
        if (radius <= 0) {
            throw new IllegalArgumentException(POSITIVE_RADIUS);
        }
        return 4 * Math.PI * radius * radius;
    }

    /**

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Pass height > 0 as the third argument: surfaceAreaCuboid(2, 3, 4).
  2. Pre-validate all dimensions together to report the true offending field.
  3. Ensure the height source is always populated for 3D calls.

Example fix

// before
double a = Area.surfaceAreaCuboid(l, w, h);
// after
if (h <= 0) throw new IllegalArgumentException("height must be > 0");
double a = Area.surfaceAreaCuboid(l, w, h);
Defensive patterns

Strategy: validation

Validate before calling

if (height <= 0) {
    throw new IllegalArgumentException("cuboid height must be > 0");
}
double a = Area.surfaceAreaCuboid(length, width, height);

Type guard

static boolean isPositiveDimension(double d) {
    return d > 0 && Double.isFinite(d);
}

Try / catch

try {
    double a = Area.surfaceAreaCuboid(l, w, h);
} catch (IllegalArgumentException e) {
    if (e.getMessage().contains("Height")) { /* height offender */ }
}

Prevention

When it happens

Trigger: surfaceAreaCuboid(2, 3, 0); surfaceAreaCuboid(2, 3, -1); valid length and width with a non-positive height.

Common situations: 2D-first code paths that default the third dimension to 0; height derived from a subtraction that went negative.

Related errors


AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13). Data as JSON: /api/errors/08151a3c155b7179. Report an issue: GitHub.