Previous | Index | Next 

[INFO] .NET floating point divisions never raise Division-by-zero errors

Math operations may deliver different results under VB6 and .NET. Most notably, under VB.NET and C# the floating-point division operator (“/”) never throws a DivisionByZero exception:

        Dim x As Double
        Dim res As Double = 1 / x    ' no error here
        Debug.WriteLine(res)         ' displays +INF 

This different behavior can be a serious problem during migrations if the original VB6 code uses an On Error Goto statement to trap divisions by zero, or uses an On Error Resume Next statement and checks the value of Err after each division:

        On Error Resume Next
        ...
        res = 1 / x
        If Err = 11 Then Debug.Print "Division by zero"

The situation is further complicated by the fact that – if both operands are zero – then VB6 raises an Overflow error rather than a Division-by-zero error.

There is no simple way to work around this issue and VB Migration Partner neither modifies the .NET in any way nor adds any warning. However, the support library exposes a special Div6 method that behaves exactly like the VB6 division operator, so that you just need to edit the original code as follows:

        '## ReplaceStatement res = Div6(1, x)
        res = 1 / x

The Div6 method is included in the VBMigrationPartner_Support module; if you add this module to the current VB6 project, you can invoke the Div6 method directly from the original VB6 code.

If you don’t like the idea of manually adding calls to the Div6 method in the original VB6 code, you can try the following PostProcess pragma:

        '## PostProcess "(?<!\^\s*)(?<n1>[^ \r\n=*()]+)\s*/\s*(?<n2>[^ \r\n=()]+)(?!\s*\^)",
            "Div6(${n1}, ${n2})"

It doesn’t cover all possible cases – for example, it doesn’t handle divisions whose operands are sub-expressions – but at least it avoids all false matches.

This is the right pragma to use when converting to C#:

        '## PostProcess "(?<!\^\s*)(?<n1>[^ \r\n=*()]+)\s*/\s*(?<n2>[^ \r\n=()]+)(?!\s*\^)",
            "VB6Helpers.Div(${n1}, ${n2})"

 

Previous | Index | Next