Pattern to handle expected errors locally, rethrow unexpected errors

后端 未结 4 916
再見小時候
再見小時候 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:52

    On Error Resume Next is the root of all evil in VBA ;)

    I have not seen your entire code but what you have asked in the question can easily be catered by using MULTIPLE ERROR HANDLERS & RESUME. It is much simpler than creating your custom Err object and raising error events...

    Public Sub sixsixsixBytes()
        On Error GoTo COMMON_ERROR_HANDLER
       'Some code...
    
        On Error GoTo ARRAY_ERROR_HANDLER
        Call Err.Raise(123)  'lets say error occured in personIndex = ....
        'it will jump to 2nd error handler and come back
        'some code again... 
        'If statement is not required at all
        Call Err.Raise(666)
    
        On Error GoTo COMMON_ERROR_HANDLER:
        'some code again...
        Call Err.Raise(234)
        Exit Sub
    
    '# MULTIPLE ERROR HANDLERS
    COMMON_ERROR_HANDLER:
        Select Case Err.Number
               Case 234: MsgBox 234
               Case 345: MsgBox 345
        End Select
    
    ARRAY_ERROR_HANDLER:
        Select Case Err.Number
               Case 123:
                    MsgBox "Name not found in person array. Using default person."
                    Resume Next 'or Resume after changing a value (as per your need)
               Case 666:
                    MsgBox "Some other error"
                    Resume Next
        End Select
    End Sub
    

提交回复
热议问题