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

前端 未结 3 784
盖世英雄少女心
盖世英雄少女心 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:45

    The reason is simple: DivideByZeroException is not designed for floating point numbers.

    According to MSDN:

    The exception that is thrown when there is an attempt to divide an integral or Decimal value by zero.

    So it's not for floating point values, though. According to IEEE 754, floating point number exceptions include:

    • Division by zero (an operation on finite operands gives an exact infinite result, e.g., 1/0 or log(0)) (returns ±infinity by default)

    You want this code if you really want to see the exception:

    static double Divide(int a, int b)
    {
        int c = 0;
        try
        {
            c = a / b;
            return c;
        }
        catch (DivideByZeroException)
        {
            Console.WriteLine("Division by zero not allowed");
            return 0;
        }
    }
    

提交回复
热议问题