unit-testingc#-4.0mathdividebyzeroexception

Divide By Zero doesn't throw DivideByZeroException with float or double...why?


I've been playing with some Math and I noticed that instead of throwing a DivideByZeroException floats and doubles get assigned the value Infinitity when you divide by zero Why is this the case?

    [TestMethod]
    public void TestFloatDivideByZero()
    {

        double myDouble = 100.0;
        var DbzDouble = 1000.0 / ((myDouble - myDouble) / myDouble);
        // Infinity

        float myFloat = 100.0f;
        var DbzFloat = 1000.0 / ((myFloat - myFloat) / myFloat);
        // Infinity

        decimal myDecimal = 100M;
        var DbzDecimal = 1000M / ((myDecimal - myDecimal) / myDecimal);
        // DivideByZeroException

        int myInt = 100;
        var DbzInt = 1000 / ((myInt - myInt) / myInt);
        // DivideByZeroException

    }

Solution

  • The floating point processor can certainly generate exceptions on division by zero. It is feature that can be turned on or off by programming the control register. That has had a very rich history of enormous pain, it scales very poorly when you mix and match libraries with different assumptions about that configuration. Extremely hard to deal with, our own legacy codebase has plenty of places where it resets the FPU after a library call.

    The prevailing conclusion was that it cannot be dealt with and that the only reasonable option is to disable the exceptions. Most any modern runtime support library follows this rule.

    The CLR is no exception, it configures the FPU to not generate exceptions and allow the processor to generate infinity. Also enshrined in the CLI standard as well as the C# language standard. If necessary you'll need to use Double.IsInfinity() to throw your own exception.