This is the code:
class Program
{
static void Main(string[] args)
{
double varrr = Divide(10, 0);
}
static double Divide(double a, double b)
{
double c = 0;
try
{
c = a / b;
return c;
}
catch (DivideByZeroException)
{
Console.WriteLine("Division by zero not allowed");
return 0;
}
}
}
I was expecting division by zero to throw a DivideByZeroException
but it did not, and when I print the result on the console the output is "Infinity". Why is that?
Any number divided by zero gives the answer “equal to infinity.” Unfortunately, no data structure in the world of programming can store an infinite amount of data. Hence, if any number is divided by zero, we get the arithmetic exception .
Microsoft Excel shows the #DIV/0! error when a number is divided by zero (0). It happens when you enter a simple formula like =5/0, or when a formula refers to a cell that has 0 or is blank, as shown in this picture.
If you divide int by 0, then JVM will throw Arithmetic Exception.
Dividing by zero is an operation that has no meaning in ordinary arithmetic and is, therefore, undefined.
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;
}
}
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;
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With