Pattern to handle expected errors locally, rethrow unexpected errors

后端 未结 4 909
再見小時候
再見小時候 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 23:00

    Though I am a bit confused by the question asked (and I've read it over quite a lot of times by now :-)), I have a very strong feeling that the source of this dilemma lies within function scopes.
    If it's ok, I will use some basic examples that show a pattern but are not 1-1 on par with your code.

    How do I segregate the expected errors I want to deal with locally, from unexpected errors to be dealt with in error handling routine (or elsewhere)?

    I kind of feel that the answer lies within the question itself.
    Error handlers are functional within the local scope of sub routines / function that you call from a lower level sub routine or function.

    I find that if I deal with some expected error numbers locally, I can't easily "rethrow" unexpected error numbers to be dealt with elsewhere.

    You can if you delegate the code that you want to check for local errors to external functions / sub routines that you place on top of a certain level in the call stack. Since they handle errors within their own scope, they won't mix up with each other.

    Consider this code:

    Sub baseSub()
    
        Dim n As Integer
    
        n = checkDivision(1, 0)      
        n = 1 / 0  ' cause an error
    
    End Sub
    
    Public Function checkDivision(iNumerator As Integer, iDenominator As Integer)
    
        On Error Resume Next
        checkDivision = iNumerator / iDenominator
    
        If Err.Number <> 0 Then
            checkDivision = Err.Number
            Exit Function
        End If
    
    End Function
    

    On the contrary: when applying On Error Resume Next from a baseSub, all functions that are placed on top of the call stack will ignore the errors as well. But, it doesn't work the other way around.

    I think you may use this to your advantage.

    So to conclude, I believe that you can solve the problem by trapping the expected errors in the delegated functions that you place on higher levels of the call stack.

    If this doesn't work, then I'm out of ideas.

提交回复
热议问题