Jump to content

Visual Basic/Error Handling

From Wikibooks, open books for an open world

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#Errors_and_Exceptions and Visual Basic/Coding_Standards#Error_Handling.