Chapter 23: Handling Errors and Exceptions
835
Note
When using error traps, one option is to redirect processing to an error trap and log the error to a log file.
After that, you could always continue processing. The result is that processing is not halted and is often suffi-
cient for situations where user intervention is not required.
One important aspect of Resume Label is that program execution is typically directed to the proce-
dure’s exit point. This gives you a handy place to put all the procedure’s cleanup code, so that it
executes regardless of whether an error occurs:
Sub LogErrors(iNumber As Integer, sDesc As String)
Dim db As DAO.Database
Dim rs As DAO.Recordset
On Error GoTo HandleError
Set db = CurrentDb()
Set rs = db.OpenRecordset(“SELECT * FROM ErrorLog”)
rs.AddNew
rs![TimeStamp] = Now()
rs![Number] = iNumber
rs![Description] = sDesc
rs.Update
ExitHere:
‘These statements are executed regardless of whether
‘an error has occurred. This section provides a single
‘place in this procedure for cleanup code:
On Error Resume Next
rs.Close
Set rs = Nothing
Exit Sub
HandleError:
‘Handle the error here
Resume ExitHere
End Sub
In this short example, the statements following the ExitHere label are executed regardless of
whether an error has occurred. You should always close recordset objects and set them to
Nothing to conserve memory. These cleanup statements normally appear near the bottom of pro-
cedures, but in this example they’re located midway through the subroutine. Execution of this pro-
cedure actually ends when the Exit Sub statement executes.
Caution
It should be recognized that the preceding example is incomplete. If the ErrorLog table doesn’t exist, an
error will be raised. You could choose to put logic in the HandleError section to create the ErrorLog
table, and use Resume to return to the OpenRecordset statement. Note that if you don’t do this, the record-
set won’t actually exist when the ExitHere section attempts to close it, so another error will be raised, creat-
ing an infinite loop.