Prefer the use of Try ... Catch
blocks instead of On Error
statements.
Visual Basic .NET and Visual Basic 2005 offer structured exception handling that provides a powerful, more readable alternative to the On
Error Goto
error handling from previous versions of Microsoft Visual Basic. Structured exception handling is more powerful because it allows
you to nest error handlers inside other error handlers within the same procedure. Furthermore, structured exception handling uses a block syntax
similar to the If...Else...End If
statement. This makes Visual Basic .NET and Visual Basic 2005 code more readable and easier to
maintain.
Noncompliant code example
Sub DivideByZero()
On Error GoTo nextstep
Dim result As Integer
Dim num As Integer
num = 100
result = num / 0
nextstep:
System.Console.WriteLine("Error")
End Sub
Compliant solution
Sub DivideByZero()
Try
Dim result As Integer
Dim num As Integer
num = 100
result = num / 0
Catch
System.Console.WriteLine("Error")
End Try
End Sub