CJ7
CJ7

Reputation: 23275

"On Error Goto 0" before Exit Function

The default error handler template in MzTools is:

On Error GoTo {PROCEDURE_NAME}_Error

    {PROCEDURE_BODY}

   On Error GoTo 0
   Exit {PROCEDURE_TYPE}

{PROCEDURE_NAME}_Error:

    MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure {PROCEDURE_NAME} of {MODULE_TYPE} {MODULE_NAME}"

Note that On Error Goto 0 is placed directly prior to the Exit statement. What is the point of doing this? It seems redundant. The error handler for the function will turn off anyway when the function exits.

Upvotes: 2

Views: 1590

Answers (2)

wqw
wqw

Reputation: 11991

It's not about turning off current error handler but about clearing Err object.

Try this

Option Explicit

Private Sub Command1_Click()
    pvTest
    MsgBox Err.Description
End Sub

Private Sub pvTest()
    On Error Resume Next
    Debug.Print 1 / 0
'    On Error GoTo 0
End Sub

Then remove commented line.

Upvotes: 3

paxdiablo
paxdiablo

Reputation: 881383

on error goto 0 turns off error handling in the current scope and reverts to the default case.

In this instance, the procedure wants an error handler to be active for the duration of the function but it wants it turned off upon exit. As you say, it's not necessary in this case since the scope of the error handler is the {PROCEDURE_TYPE} so it will be reverted on exit.

But sometimes, coders (especially those that generate templates) like to clean up after themselves even when not technically necessary, such as freeing allocated memory in a C program before exiting.

That's what I suspect is the case here, that it really is just supposition.

Upvotes: 3

Related Questions