PDA

View Full Version : Error handling approach



Jfp87
05-02-2017, 12:53 AM
Guys,

I am adding a document variable and I am specifically handling the case where the variable already exists in the document (code is just a snippet):



On Error Resume Next
Err.Clear


oDoc.Variables.Add VariableName, VariableValue


If Err.Number = 5903 Then
''''''''''''''''''''''''''''''''''''''''
'The variable name already exists.
'Edit the existing variable value.
''''''''''''''''''''''''''''''''''''''''
oDoc.Variables(VariableName).Value = VariableValue
Err.Clear
End If


On Error GoTo 0


I'm pretty sure that the above is sufficient for almost everything however, after having a think about it, is the following better? (snippet):


oDoc.Variables.Add VariableName, VariableValue


Select Case Err.Number


Case 0
'''''''''''''''''''''''''''''''''''''''''''
'No error. Do nothing - variable was added.
'''''''''''''''''''''''''''''''''''''''''''


Case 5903
'''''''''''''''''''''''''''''''''''''''''''
'Variable name already exists. Edit existing.
'''''''''''''''''''''''''''''''''''''''''''
oDoc.Variables(VariableName).Value = VariableValue

Case Else
'''''''''''''''''''''''''''''''''''''''''''
'An unanticipated error occurred - exit.
'''''''''''''''''''''''''''''''''''''''''''

Err.Clear
Exit Function


End Select


I'm not sure if it's overkill but the way I see it, only 1 of 3 things are going to happen:

1) No error (0)
2) Variable exists (5903)
3) Something else

I'm not even sure if it is possible for another error to occur, but I thought it was more robust to deal with it in that way. Any suggestions?

Cheers,
Joe

gmaxey
05-02-2017, 03:03 AM
I don't see why the first approach wouldn't do though you don't need the Err.clear line.

If I was going to try to catch an unknown error that shouldn't occur, I probably would do something like this:



Sub ScratchMacroII()
'A basic Word macro coded by Greg Maxey
On Error GoTo Err_Var
ActiveDocument.Variables.Add "A", "B"
ActiveDocument.Variables.Add "A", "B"
lbl_Exit:
Exit Sub
Err_Var:
Select Case Err.Number
Case 5903
Case Else: MsgBox Err.Number & " " & Err.Description
End Select
Resume Next

End Sub

Jfp87
05-02-2017, 04:08 AM
Thanks for that Greg. Yeah, I see the err object is cleared when using any On Error statement so I will remove that line.

Your method also seems more logical so I will use something similar. Cheers.

gmayor
05-02-2017, 04:35 AM
Or you could simply write the value to the named variable and there wouldn't be an error whether it exists or not.

ActiveDocument.Variables("A").Value = "B"