INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Jobs

Visual Basic (Microsoft) Versions 5/6 FAQ

VB Programming Concepts

Error Handling by CasperTFG
Posted: 26 Mar 02

Through helping people out with their code I have noticed one thing which a lot of new programmers are missing.  Error Handling is the most important part of your code beside the actual code that does the work.  A good programmer knows that you should never have an un-handled error.

What is an un-handled error?
An unhandled error is any error that happens in your code that you allow windows to deal with.  If you fail to include error handling in your code, then a simple error such as a file that you try to open went missing will cause your entire program to crash.  If you handle the error in your code, then you can save it from crashing and possibly recover the error.

Helpful Error Handling Commands
On Error GoTo û This command will tell the program that If an error should occur you should go to this portion of code.
ErrorHandler: û This is a line label.  It marks the start of a section of code.  Anytime you place a : after a word this marks a line label.
On Error Resume Next û This code will tell your program to ignore any errors that may occur.
err û The err function has many values, it can pass you the desciption, the error number, and etc.  There are also variations on this, such as ADOerr

How to Handle the Errors in your Code
Here is a sample of Error Handling in a Command button

Private Sub Command1_Click()
On Error GoTo ErrorHandler
    
    ÆInclude Your Code Here
    

Exit Sub ÆInclude this line to unsure that if the code runs without problem it wonÆt hit the error handler
ErrorHandler:
    ÆInclude Your Error Handling Code Here
End Sub

You can See by the above code, the first line is On Error GoTo. This is done so that If an error should occur at any point throughout this entire function the error will be handled.  However if there is a specific piece of code that you are worried may kick up an error (such as opening a file), this can be done with specific error handling.  Like this:

Private Sub Command1_Click()
    
    ÆInclude Your Code Here
    

On Error GoTo FileError ÆPlace this right before the line that may cause an error
    
    ÆInclude Your Code Here
    

Exit Sub ÆInclude this line to unsure that if the code runs without problem it wonÆt hit the error handler
FileError:
    ÆInclude Your Error Handling Code Here
End Sub


If the error that occurs is not a big error more of a small glitch, then you may want to continue on with your code.  Such as If you are looking for a value from a file, but the file is gone, you donÆt want to have your program stop and fail, instead you could continue on with a default value or the next line of code.  The Resume Next function is ideal for this.

Private Sub Command1_Click()
On Error Resume Next
    
    ÆInclude Your Code Here
    

End Sub


Bringing them all together
Now that we know several types of error Handling lets put them together into one.

Private Sub Command1_Click()
On Error GoTo ErrorHandler
    
    ÆInclude Your Code Here
    

On Error GoTo FileError ÆPlace this right before the line that may cause a file error
    
    ÆInclude File opening code here
    

On Error GoTo ErrorHandler ÆPlace this right after the line that may cause a file error to resume regular error handling
    
    ÆPut in the rest of your code here
    

Exit Sub ÆInclude this line to unsure that if the code runs without problem it wonÆt hit the error handler
FileError:
    ÆInclude Your Error Handling For not being able to open the file
Exit Sub ÆInclude this line to unsure that if the code runs without problem it wonÆt hit the error handler
ErrorHandler:
    ÆInclude Your Error Handling Code Here
Resume Next Æthis will tell the Program to continue on with the rest of the code.
End Sub


Deciding how to Handle Errors
Depending on how you want your program to look to a user will help you decide on how to handle errors.  A program to be used internally in a company might not have to be as clean looking, so you could simply use a message box to display the error.  However if you want to sell this product, then the last thing your user should see is errors popping up.  In fact they should never see an error pop-up, this will give the illusion that there are no problems with your code.  These should be handled by logging the error to a file.

Visible Errors
This type of error Handling is good for debugging your own code, or for errors that would cause the program to stop anyway.

ErrorHandler:
    ÆInclude Your Error Handling Code Here
    MsgBox ôAn Error Occurredö & vbCrLf & _
        ôError Number: ô & err.Number & vbCrLf & _
        ôError Description: ô & err.Description, vbOkOnly, ôProgram Errorö
End Sub


Handled Errors
This is the best way to handle errors.  If you know how to fix the given error then fix it.

ErrorHandler:
    ÆInclude Your Error Handling Code Here
    Select Case err.Number
        Case 90 ÆThis is a database Error
            ÆCode to re-connect to database
        Case Else
            MsgBox ôAn Error Occurredö & vbCrLf & _
                ôError Number: ô & err.Number & vbCrLf & _
                ôError Description: ô & err.Description, vbOkOnly, ôProgram Errorö
    End Select
End Sub


Hidden or logged Errors
This way of handling errors is the preferred.  It hides the error from the user, but logs it to a file instead.  This is useful so that the user never sees the error, but if they report a problem to you, then you can ask for the error log to see what happened.  I Usually pass this to a separate function to keep it clean in the code.

ErrorHandler:
    ÆInclude Your Error Handling Code Here
    Call GlogalErr(err.Number, err.Description, ÆAny additional Parameters.)
End Sub

ÆMy Global Error handler for all error Handling
Public Function GlobalErr(ByRef ErrNo As Integer, ByRef ErrDesc As String, ByRef Message As String)
    Dim FileNum As Integer
    Dim strDate As String
    NL = Chr(10)
    FileNum = FreeFile
    strDate = Format(Date + Time, "YYYY/MM/DD hh:mm:ss   ")
    
    Open App.Path & "\ErrorLog.txt" For Append Shared As #FileNum
    Print #FileNum, strDate & ErrNo & ErrDesc & Message
    Close #FileNum
End Function


Additional Error Handling
There are many other types of error handling you can look at.  I would suggest going to http://support.microsoft.com/ and checking it out.  There are neat things such as ADO errors if youÆre using ADO, and ReRaise Error.

Useful Stuff
Now that IÆve badgered you with all this neat stuff, IÆll give you something Useful.  YouÆll notice that IÆm using a variable called myName.  This is very useful in debugging your code, you change the value of myName for each Sub or Function, this way, not only do you get the error reported but you also get to see which function the error was triggered in.

ÆPlace this code in each and every one of your code modules
Private Sub SampleCodeSub(ByVal PassedValue as String)
On Error GoTo ErrorHandler
    Dim myName as String
    ÆSet MyName equal to the name of the function or sub, and include any passed values
    MyName = ôCommand1_Click( PassedValue=ö & PassedValue & ô)ö

    ÆInclude the body of your program here

Exit Sub æ/or Function
ErrorHandler:
    ÆInclude Your Error Handling Code Here
    Call GlogalErr(err.Number, err.Description, ÆAny additional Parameters.)
    Resume Next
End Sub æ/or Function

ÆPlace this code once in your main code module
Public Function GlobalErr(ByRef ErrNo As Integer, ByRef ErrDesc As String, ByRef Message As String)
    Dim FileNum As Integer
    Dim strDate As String
    NL = Chr(10)
    FileNum = FreeFile
    strDate = Format(Date + Time, "YYYY/MM/DD hh:mm:ss   ")
    
    Open App.Path & "\ErrorLog.txt" For Append Shared As #FileNum
    Print #FileNum, strDate & ErrNo & ErrDesc & Message
    Close #FileNum
End Function


And that my friends is error handling in a nutshell...

Back to Visual Basic (Microsoft) Versions 5/6 FAQ Index
Back to Visual Basic (Microsoft) Versions 5/6 Forum

My Archive

Resources

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close