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
See also  Professionalism Starts in Your Inbox: Keys to Presenting Your Best Self in Email
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist