Float, Double, Decimal Types and DivideByZeroException

Most of us know the difference between Float, Double and Decimal types in .Net is the precision.

  • Float 32 bit (7 digits)
  • Double 64 bit (15-16 digits)
  • Decimal 128 bit (28-29 digits)

But most of us scratch our head over this:

var numerator = 10;
var denominator = 0;
var resultNoException1 = (float)numerator / (float)denominator; // Result Infinity, does not throw exception
var resultNoException2 = (double)numerator / (double)denominator; // Result Infinity, does not throw exception
var resultException = (decimal)numerator / (decimal)denominator; // Throw DivideByZeroException

Suffice to say throw/catch block won’t caught any exception on resultNoException1 and resultNoException2.

Why?

Because Float and Double types are binary floating point types (or sometimes being referred to as floating point types) while Decimal is decimal floating point types.

From MSDN:

Dividing a floating-point value by zero doesn’t throw an exception; it results in positive infinity, negative infinity, or not a number (NaN), according to the rules of IEEE 754 arithmetic.