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 an chief architect at Avior A/S, a consultancy firm in Copenhagen, Denmark. He holds a degree in software engineering specializing in software development. His primary expertise are the Microsoft .Net framework and SQL Server which he has been working with since the start of this century! He enjoys discussing technical topics, teaching and speaking at conferences.


Tags:

One Response to “When is DivideByZeroException thrown?”

  1. AfshinNo Gravatar says:

    This is my problem too.
    I found your note after a long while, searching the net. Thanks for sharing that

Leave a Reply