When is DivideByZeroException thrown?

What a strange question most developers will say. DivideByZeroException
is thrown every time you divide by zero, right? No – it depends.

Let’s try – regular division with integers.

int i1 = 4;
int i2 = 0;

try
{
Console.WriteLine(i1 / i2);

}
catch (System.DivideByZeroException)
{
Console.WriteLine("DivideByZeroException");
}

Hmm, I see a DivideByZeroException coming, and that’s
absolutely correct. So what is all the fuzz about?

Let’s try again, but this time with floating point numbers.

double d1 = 4.0;
double d2 = 0.0;

try
{
Console.WriteLine(d1 / d2);

}
catch (System.DivideByZeroException)
{
Console.WriteLine("DivideByZeroException");
}

If you try to run this piece of code, no exception is
thrown. Instead INF (short for infinite) is returned. To be more precise a PositiveInfinity,
due to the decimalNumerator is positive.

I read this somewhere and had to test it. I even asked
my colleagues when DivideByZeroException is thrown and showed them these code examples.
None of them knew the right answer. So it’s not only me, whom is ignorant. :-)


 Anders Lybecker is a Technical Evangelist at Microsoft Denmark. He holds a degree in software engineering specializing in software development. He is well founded in .Net which he has been working with since the start of this century!


One thought on “When is DivideByZeroException thrown?

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>