In Dutch: “Delen door nul is flauwekul”, which means “dividing a number by zero is nonsense“.

When you start programming you have probably experienced this: the .Net DivideByZeroException. You get this when, for instance, you want to calculate the average of a values list, and you divide it by the number of items, but then the list is empty, so you divide by zero. The .Net framework then throws a nice DivideByZeroException, which points you to the place in the code were you did not check for the denominator to be zero.

So, then all is well. Until you start calculating with doubles in stead of integers. Then you do not get an exception when you divide by zero. Instead, the double gets one of the following three values:

  • PositiveInfinity
  • NegativeInfinity
  • NaN

The first you get by dividing a positive value by zero, the second by deviding a negative value by zero and the last one by deviding zero by zero. Following the docs, when you want to check whether a double has one of these three values, you cannot check it this way:

d == Double.PositiveInfinity, d == Double.NagativeInfinity,  d == Double.NaN

But you have to use these methods instead:

  • Double.IsPositiveInfinity(d)
  • Double.IsNagativeInfinity(d)
  • Double.IsNaN(d)

calculator

Dividebyzeroexception

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s