Search code examples
c++divisiondivide-by-zero

Appropriate behaviour to prevent division by zero


We have been asked to design a Vector3D class using memory on the stack. I need to divide the vector by a scalar, but what is the most appropriate behavior to prevent a divide by zero? I could throw an exception? I don't want to return a Vector3D of (0,0,0) because that would suggest that the operation was successful, when in fact it wasn't.

Vector3DStack Vector3DStack::operator / (float s) const
{
    if (s == 0)
    {
        // How should I handle division by zero?
        // Method is expecting a Vector3DStack to be returned.

    }

    return Vector3DStack(x / s, y / s, z / s);
}

Solution

  • You should definitely throw an exception.That is what exceptions are for - to indicate exceptional circumstances in your code. Actually you may allow a small tolerance around zero too, for instance:

    Vector3DStack Vector3DStack::operator / (float s) const
    {
        if (fabs(s) < 1e-10) {
          ... throw some exception to indicate you are dividing a vector by zero.
        }
        return Vector3DStack(x / s, y / s, z / s);
    }