In Visual Basic, the error handling constructs On Error (VB6) and Try...Catch (VB.NET) are used for error handling.
On Error GoTo <Label> — an outdated method from VB6 that implements a jump to the specified label on error. It does not support nesting and can lead to convoluted code.Try...Catch...Finally — the modern method (VB.NET) that allows working with exceptions, providing the ability to handle different types of errors in different Catch blocks and ensuring final actions are always executed in Finally.Examples:
VB6:
Sub OpenFile() On Error GoTo ErrorHandler Open "file.txt" For Input As #1 ' Reading the file Close #1 Exit Sub ErrorHandler: MsgBox "Error: " & Err.Description End Sub
VB.NET:
Sub OpenFileVBNet() Try Using reader As New StreamReader("file.txt") Dim line As String = reader.ReadLine() End Using Catch ex As IOException MsgBox("Error: " & ex.Message) Finally ' Always executed End Try End Sub
If an error occurs in VB6 in the On Error Resume Next block, how can you find out where exactly it happened and how to handle it correctly?
Correct answer:
In On Error Resume Next mode, the program continues execution at the next line. To determine if an error occurred, you need to check the Err object after the call.
On Error Resume Next ' some code If Err.Number <> 0 Then MsgBox "Error: " & Err.Description Err.Clear End If
Story
After transitioning from VB6 to VB.NET, some error handlers were left in the On Error GoTo style, leading to implicit swallowing of errors. The logic of processing was mixed up, causing data in the database to remain semi-empty, and the bug was discovered only months later.
Story
Did not use Err.Clear, resulting in Err.Number remaining non-zero after one handled error. During further checks, the program incorrectly thought a new error had occurred and went into incorrect branches of handling.
Story
During refactoring, forgot to remove On Error Resume Next, which caused errors to be "swallowed" and no messages to be generated. Diagnosing the problems took hours, as the application seemed to be functioning normally but was actually losing important data.