This is the code:
class Program
{
static void Main(string[] args)
{
double varrr = Divide(10, 0);
}
static double Divide(double a, d
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;
}
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;
}
}
Dividing a floating-point value by zero doesn't throw an exception; it results in positive infinity, negative infinity, or not a number (NaN), according to the rules of IEEE 754 arithmetic. Because the following example uses floating-point division rather than integer division, the operation does not throw a DivideByZeroException exception.
https://msdn.microsoft.com/en-us/library/system.dividebyzeroexception(v=vs.110).aspx