Divide by Zero


What will be the out put of the following code:


try
{
   
double k = 19;   double m = 0;
   k = k / m;
  
Console.WriteLine(Convert.ToString(k));
  
Console.Read();
}
catch (Exception ex)
{
   Console.WriteLine(ex.Message);
}


Different data type behave differently for divide by zero exception.


The above code does not throw devide by zero exception, but it will quitly execute and ‘k’ will have the value of ‘infinity’. So, don’t depend on a exception here. However, if ‘k’ and ‘m’ are int then you will get the divideByZero exception


 

Comments (4)

  1. You’ve been kicked (a good thing) – Trackback from DotNetKicks.com

  2. Steve Kaschimer says:

    From MSDN:

    The Double value type represents a double-precision 64-bit number with values ranging from negative 1.79769313486232e308 to positive 1.79769313486232e308, as well as positive or negative zero, PositiveInfinity, NegativeInfinity, and Not-a-Number (NaN).

    The floating-point operators, including the assignment operators, do not throw exceptions. Instead, in exceptional situations, the result of a floating-point operation is zero, infinity, or NaN, as described below:

    – If the result of a floating-point operation is too small for the destination format, the result of the operation is zero.

    – If the magnitude of the result of a floating-point operation is too large for the destination format, the result of the operation is PositiveInfinity or NegativeInfinity, as appropriate for the sign of the result.

    – If a floating-point operation is invalid, the result of the operation is NaN.

    – If one or both operands of a floating-point operation are NaN, the result of the operation is NaN.

  3. The C# team is happy to welcome you to the new look of the C# Developer Center. This is the home page…

  4. The C# team is happy to welcome you to the new look of the C# Developer Center. This is the home page…

Skip to main content