Pattern to handle expected errors locally, rethrow unexpected errors

后端 未结 4 899
再見小時候
再見小時候 2021-02-13 22:16

Sometimes a certain bit of code will raise an error in an expected way, and it\'s most convenient to handle it locally rather than throw it to an error handling routine where it

4条回答
  •  执笔经年
    2021-02-13 22:55

    I made a user-defined type that has the same members as the Err object (Number, Source, Description, etc.). The SaveErr function will basically copy the values of the Err object properties into a variable of this type, and RaiseSavedErr will raise an error using those property values.

    Of course the exact same thing could be done using a class and methods instead of a user-defined type and functions/subs. But the idea would be the same.

    Example:

        On Error Resume Next
        personIndex = FindInArray(personName, personArray)
        savedErr = SaveErr(Err) 'Save values of Number, Source, Description, etc.
        On Error GoTo ErrorHandler
        'Segregate error handling strategies here using savedErr
        If savedErr.Number = ERR__ELEMENT_NOT_FOUND_IN_ARRAY Then
            MsgBox "Name not found in person array. Using default person."
        Else
            RaiseSavedErr savedErr 'rethrows the error
        End If
    

    I'd like to know if there is a more standard or elegant way of doing this.

提交回复
热议问题