devxlogo

Avoid Exit Sub and Exit Function

Avoid Exit Sub and Exit Function

It is bad programming practice to exit a subroutine or function at any point other than its end. If you want to bail out of a routine, and do not want to keep nesting “If” clauses to handle the various error criteria that make you want to exit the routine, use the Raise method on the Err object instead. You can create your own error code, and document in the error handler why you are bailing out of the routine. This allows subsequent developers to better understand what your code is doing and why. Use your judgement though–being lazy and using an error handler to avoid maintaining an If block structure is not much better than using an “Exit Function” statement.

 Private Function CalcTotal(Cust as clsCust) as Long    On Error GoTo ProcErr    If Cust.SalesType = "INTERNAL" Then        'Don't do "Exit Function" here!!        Err.Raise vbObjectError + 1    End If    '    'Proceed with normal calculation    '    Exit Function 'Don't go into error handlerProcErr:    Select Case Err        'Error 1 occurs when an internal customer is sent        'for calculation.  This should never really happen,        'so we set its total to 0        Case vbObjectError + 1            CalcTotal = 0        Case Else            'untrapped error handling required    End SelectEnd Function

devx-admin

Share the Post: