BaldyWeb

Adding Error Handling to Your Code

As you write more complicated code and distribute your applications to other people, you will need to start adding error handling to your code.  In all cases it makes for more professional handling of unanticipated errors, and in runtime applications if an unhandled error occurs the application will quit.  Error handling will prevent that.  Here are the basics:

Private Sub Whatever()
  Dim db As DAO.Database   'These two lines are just an example
  Dim rs As DAO.Recordset  'your code may not include them
  On Error GoTo ErrorHandler

  'Your code here

ExitHandler:   'clean up as necessary and exit
  Set rs = Nothing  'These two lines are just an example
  Set db = Nothing  'your code may not include them
  Exit Sub
ErrorHandler:
  Select Case Err  'specific Case statements for errors we can anticipate, the "Else" catches any others
    Case 2501       'Action OpenReport was cancelled.
      MsgBox "No data to display"
      DoCmd.Hourglass False
      Resume ExitHandler
    Case Else
      MsgBox Err.Description
      DoCmd.Hourglass False
      Resume ExitHandler
  End Select
End Sub

 

Home