Why doesn't dividing by zero with doubles throw an exception?

前端 未结 3 794
盖世英雄少女心
盖世英雄少女心 2020-12-11 10:21

This is the code:

class Program
{
    static void Main(string[] args)
    {
        double varrr = Divide(10, 0);
    }

    static double Divide(double a, d         


        
3条回答
  •  北荒
    北荒 (楼主)
    2020-12-11 10:36

    MSDN explains that DivideByZeroException is only thrown "[when] trying to divide an integer or decimal number by zero", whereas

    floating-point operations return PositiveInfinity or NegativeInfinity to signal an overflow condition.

    Use Double.IsInfinity() instead:

    if (double.IsInfinity(c))
    {
        Console.WriteLine("Division by zero not allowed");
        return 0;
    }
    

提交回复
热议问题