Divide By Zero

I learned something today. This code:

Dim input1 As Double = 5
Dim output1 As Double = (input1 / 0)

…will not throw a System.DivideByZeroException.

It actually returns Double.PositiveInfinity.

Debug.Print(output1.ToString)

…results in “Infinity”.

Debug.Print(Double.IsInfinity(output1))
Debug.Print(Double.IsPositiveInfinity(output1))
Debug.Print(Double.PositiveInfinity = output1)

All result in “True”.

A Single Type has the identical behavior.

In spite of the documentation for System.DivideByZeroException, my testing shows that an Integer Type displays the same behavior.

Dim input1 As Integer = 5
Dim output1 As Double = (input1 / 0)

…will return Double.PositiveInfinity. Be careful with this one – I’m always leery of something that blatantly contradicts the documentation.

The Decimal Type does respond the way I expect:

Dim input1 As Decimal = 5
Dim output1 = (input1 / 0)

…does indeed throw a System.DivideByZeroException.

If you’re using strongly-typed variables, this will rarely be a problem. The danger comes when we don’t strongly type our variables and don’t have Option Strict On. The following is perfectly acceptable code:

Dim input1 As Double = 5
Dim input2 As Double = 0
Dim dangerousOutputString = (input1 / input2).ToString

The output, however, is anything but acceptable: dangerousOutputString now contains the string “Infinity”.

Advertisements