0

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?

Hossein Ebrahimi
  • 632
  • 10
  • 20
  • According to [here](https://learn.microsoft.com/en-us/dotnet/api/system.convert.todouble?view=netcore-3.1) one of the exceptions that the conversion may throw is overflow exception. Why I'm not getting anything? – Hossein Ebrahimi Aug 02 '20 at 11:03
  • No, it does not throw for most overflow situations, as you already observed. Also note that the `checked` (and likewise for `unchecked`) keyword only applies to the code compiled directly into the block inside, it does not apply to methods being called from inside the block. – Lasse V. Karlsen Aug 02 '20 at 11:04
  • 1
    It will cause an exception if you try to convert a too big a number to a double, but it will not throw if you, say, add two big numbers that overflows. Inconsistent, I know, but that's how it is. – Lasse V. Karlsen Aug 02 '20 at 11:04
  • [It can](https://stackoverflow.com/questions/14462072/untraceable-exceptions-in-windows-forms-application-run). – Hans Passant Aug 02 '20 at 13:55
  • In [here](https://learn.microsoft.com/en-us/dotnet/api/system.double.parse?view=netcore-3.1) it says: OverflowException .NET Framework and .NET Core 2.2 and earlier versions only: s represents a number that is less than MinValue or greater than MaxValue. However, it's about double.Parse. – Hossein Ebrahimi Aug 05 '20 at 12:34

2 Answers2

1

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.

Joni
  • 108,737
  • 14
  • 143
  • 193
1

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.

Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197