Generic Error Handler

D

David

Hello all,
I typically write the error handling towards the end of development.

I saw this bit of code in a response from '69 Camaro, can I use this genreic
error handler marked with *'s at the end of the line for any/all events in my
subs?

Private Sub blah blah blah event()

On Error GoTo ErrHandler '**

'blah blah blah code

ErrHandler: '**

MsgBox "Error in" & vbCrLf & Me.Name & _ **
" form." & vbCrLf & vbCrLf & _ **
"Error #" & Err.Number & vbCrLf & Err.Description **
Err.Clear **

End Sub
 
D

Douglas J Steele

Yeah, you can do that. And if you pickup MZTools from http://www.mztools.com
, you can have it automatically inserted for you, rather than having to type
it.

Personally, I prefer the following style:

On Error GoTo ErrHandler

'blah blah blah code

EndIt:
' Put any cleanup-type code here, so that
' it's executed whether or not an error arises
Exit Sub

ErrHandler:

MsgBox "Error in" & vbCrLf & Me.Name & _
" form." & vbCrLf & vbCrLf & _
"Error #" & Err.Number & vbCrLf & Err.Description
Resume EndIt

End Sub

I also prefer to call a routine (mine's called DisplayError), rather than
simply building the MsgBox in each routine because that way I can also write
the error details to a text file, or to a table, or other such options, and
I only have to change what I want to do in one place.
 
D

David

Douglas,
Thank you for the info. and quick response. Be patient with me here.....

I would like to be as efficient as possible. If I am understanding you
correctly, I can create a function to handle errors called DisplayError and
only put this one line at the top of each sub event?
 
D

Douglas J Steele

No.

What I meant is that I use

ErrHandler:
Call DisplayError Err, Me.Name & ".MyEvent
Resume EndIt

rather than

ErrHandler:
MsgBox "Error in" & vbCrLf & Me.Name & _
" form." & vbCrLf & vbCrLf & _
"Error #" & Err.Number & vbCrLf & Err.Description
Resume EndIt

A simplified version of DisplayError is:

Sub DisplayError(ErrObj As VBA.ErrObject, Location As String)

MsgBox ErrObj.Description & " (" & ErrObj.Number & ") encountered in " &
Location, _
vbOKOnly + vbCritical

End Sub

(as I said, I often have optional parameters, such as DebugFG, as well)
 
D

Douglas J Steele

Ooops, that should have been either

Call DisplayError(Err, Me.Name & ".MyEvent)

or

DisplayError Err, Me.Name & ".MyEvent
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top