Better handling of "on error goto" statements in Visual Basic 6.

Published : 22.Jun.2006

Every procedure or function within my Visual Basic applications, use an On Error statement much like the one shown below, which runs a global error handling procedure gErrHandler, whenever there is a problem within the code.

Sub Main

On Error GoTo ErrLabel

    ... code here

Exit Sub

ErrLabel:
    gErrHandler Null, Null, strProcName, strDBAction
End Sub

Now in the production software, this global error handling procedure logs the exact error to a log file, and presents the user with a nice dialog box explaining the problem, and then unloads all the forms and closes the application.

This is a nice desired action in the final EXE program, but does make debugging via the IDE much harder, and up till now I have been commenting out the On Error statement while testing, and having to remember to un-comment the line when building the EXE.

Well I finally got sick of doing this, there had to be some way of detecting if the program is being run as a compiled EXE, or being run via the IDE, and only set the On Error statement when running as an compiled EXE.

Global Procedure bIsEXE()

Now all my applications use this global procedure which returns a boolean True if the program is being run as a compiled EXE, or False if the program is being run from the Visual Basic IDE.

Public Function bIsEXE() As Boolean
    On Error GoTo IDEInUse
        
        'division by zero error will only
        'run in IDE when using Debug.Print
        Debug.Print 1 \ 0
        
        bIsEXE = True
        Exit Function

IDEInUse:
     'division by zero error got us here
     'so we must be running under the IDE
     bIsEXE = False
End Function

This now allows me to do the following check below, which only runs the On Error statement when the program is being run as an EXE, and saves having to comment/un-comment the line when testing and debugging the code via the IDE.

Sub Main

    If bIsEXE = True Then On Error GoTo ErrLabel

        ... code here

    Exit Sub

ErrLabel:
    gErrHandler Null, Null, strProcName, strDBAction
End Sub

What Next?

Bookmark this article at :-

 

About Author:
I'm a father, husband, and a software developer who works for the NHS. more »

Sections :
« Articles
« Contact


 

EditPlus Text Editor - an Internet-ready 32-bit text editor, with syntax highlighting for HTML, PHP, CSS and more.