Error Handling Transformation
Visual Basic 6.0 and the .NET languages have different error handling techniques; while VB.NET is able to support a small subset of VB6 error handling keywords, C#.NET is not. Also, VB6 features in-code labels that can be used to create confusable “jump” patterns. These patterns are complex to read in VB6 and need to be removed from the resulting code for the sake of maintainability.
The Visual Basic Upgrade Companion is able to remove unstructured “spaghetti code” and convert it to structured .NET statements. All unused labels are removed from the resulting code, plus the most commonly used “On Error” patterns are currently recognized and replaced for native .NET equivalent “try … catch” blocks.
As part of the full conversion of the Visual Basic 6 Error handling schema (On Error ... Goto) to .NET, it is also necessary to convert the Err Object.
The following VB6 extract shows a simple usage of the “On Error” statement to avoid a possible division by zero. The flow control of this source code extract will jump to the “ErrorHandler:” label in case there is an arithmetic error.
Original VB6 source code
Public Sub ErrorHandling(arg1 As Integer)
On Error GoTo ErrorHandler
Dim var1 As Integer
var1 = 1 / arg1
MsgBox var1
MsgBox arg1
Exit Sub
ErrorHandler:
MsgBox Err.Description, , "Error"
End Sub
The Upgrade Wizard converts it using the same error management statements as in the original VB6 source code.
VB.NET code generated by the Upgrade Wizard
Public Sub ErrorHandling(ByRef arg1 As Short)
On Error GoTo ErrorHandler
Dim var1 As Short
var1 = 1 / arg1
MsgBox(var1)
MsgBox(arg1)
Exit Sub
ErrorHandler:
MsgBox(Err.Description, , "Error")
End Sub
The Visual Basic Upgrade Companion is able to generate VB.NET source code using the .NET “Try Catch” blocks by applying special refactor techniques, as well as the same error management patterns from VB6 if needed. If the resulting language is C# the “try catch” generation is mandatory.
VB.NET code generated by the Visual Basic Upgrade Companion
Public Sub ErrorHandling(ByRef arg1 As Integer)
Try
Dim var1 As Integer
var1 = 1 / arg1
MessageBox.Show(CStr(var1), Application.ProductName)
MessageBox.Show(CStr(arg1), Application.ProductName)
Catch excep As System.Exception
MessageBox.Show(excep.Message, "Error")
End Try
End Sub
C#.NET code generated by the Visual Basic Upgrade Companion
public void ErrorHandling( int arg1)
{
try
{
int var1 = 0;
var1 = Convert.ToInt32(1 / ((double) arg1));
MessageBox.Show(var1.ToString(), Application.ProductName);
MessageBox.Show(arg1.ToString(), Application.ProductName);
}
catch (Exception excep)
{
MessageBox.Show(excep.Message, "Error");
}
}