Does C# throw OverflowException for floating point numbers?

731 Views Asked by At

Does C# compiler throw OverflowException for floating-point numeric types?

I tried this to figure it out:

try
{
    checked
    {
        double d = Convert.ToDouble(Math.Pow(double.MaxValue, double.MaxValue));
        Console.WriteLine(d);
    }
}
catch (OverflowException)
{
    throw;
}

and what I saw in the console window was an ∞.

Is ∞ more useful when debugging than an exception?

2

There are 2 best solutions below

0
Joni On BEST ANSWER

No, C# does not have exceptions for floating point operations.

The floating point type has 3 special values: positive infinity, negative infinity, and "not a number".

If the result of a calculation is greater than what can be represented, it overflows without an exception being thrown and the result is positive infinity. is how it's represented in a string.

0
Vivek Nuna On

It is no exception, It is showing you the correct value i.e. INFINITY ().

You can check that also by bool isInfinity = double.IsInfinity(d);

It will also return true for bool isInfinity = double.IsInfinity(1.0/0);

I am using .Net core 3.1.