Visual Basic/Error Handling

Error handling in Visual Basic, an outline:

  • On Error Goto <Label>
  • On Error Goto 0
  • On Error Resume Next
  • If Err.Number = 0
  • If Err.Number <> 0
  • Resume
  • Resume <Label>
  • Resume Next
  • Err.Description
  • Err.Raise <Number>

Suppressing the error and detecting it using the non-zero error numberː

Set MyCollection = New Collection
MyCollection.Add "Item", "Item"
On Error Resume Next
MyCollection.Add "Item", "Item" 'This result in an error
MyErrNumber = Err.Number
On Error Goto 0 'Restore the absence of error handling
If MyErrNumber <> 0 Then
  'Error occurred
  MsgBox "Item already present in the collection."
End If

Creating an error handlerː

Sub Test()
  On Error Goto ErrorHandler
  ...
  Exit Sub

ErrorHandler:
  ...
End Sub

Creating an error handler that differentiates per error numberː

Sub Test()
  On Error Goto ErrorHandler
  ...
  Exit Sub

ErrorHandler:
  Select Case Err.Number
  Case 0
    'No error
  Case 5
    '...
  Case Else
    '...
  End Select
End Sub


See also Visual Basic/Effective Programming and Visual Basic/Coding Standards.

Category:Book:Visual Basic#Error%20Handling%20
Category:Book:Visual Basic