Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Error Handling

VB Programming Concepts

Error Handling

by  CasperTFG  Posted    (Edited  )
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. [color blue]A good programmer knows that you should never have an un-handled error.[/color]

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 û [color green]This command will tell the program that If an error should occur you should go to this portion of code.[/color]
ErrorHandler: û [color green]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.[/color]
On Error Resume Next û [color green]This code will tell your program to ignore any errors that may occur.[/color]
err û [color green]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[/color]

How to Handle the Errors in your Code
Here is a sample of Error Handling in a Command button
[tt]
Private Sub Command1_Click()
On Error GoTo ErrorHandler
[color green]
ÆInclude Your Code Here
[/color]
Exit Sub [color green]ÆInclude this line to unsure that if the code runs without problem it wonÆt hit the error handler[/color]
ErrorHandler:
[color green]ÆInclude Your Error Handling Code Here[/color]
End Sub
[/tt]
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:
[tt]
Private Sub Command1_Click()
[color green]
ÆInclude Your Code Here
[/color]
On Error GoTo FileError [color green]ÆPlace this right before the line that may cause an error[/color]
[color green]
ÆInclude Your Code Here
[/color]
Exit Sub [color green]ÆInclude this line to unsure that if the code runs without problem it wonÆt hit the error handler[/color]
FileError:
[color green]ÆInclude Your Error Handling Code Here[/color]
End Sub
[/tt]

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.
[tt]
Private Sub Command1_Click()
On Error Resume Next
[color green]
ÆInclude Your Code Here
[/color]
End Sub
[/tt]

Bringing them all together
Now that we know several types of error Handling lets put them together into one.
[tt]
Private Sub Command1_Click()
On Error GoTo ErrorHandler
[color green]
ÆInclude Your Code Here
[/color]
On Error GoTo FileError [color green]ÆPlace this right before the line that may cause a file error[/color]
[color green]
ÆInclude File opening code here
[/color]
On Error GoTo ErrorHandler [color green]ÆPlace this right after the line that may cause a file error to resume regular error handling[/color]
[color green]
ÆPut in the rest of your code here
[/color]
Exit Sub [color green]ÆInclude this line to unsure that if the code runs without problem it wonÆt hit the error handler[/color]
FileError:
[color green]ÆInclude Your Error Handling For not being able to open the file[/color]
Exit Sub [color green]ÆInclude this line to unsure that if the code runs without problem it wonÆt hit the error handler[/color]
ErrorHandler:
[color green]ÆInclude Your Error Handling Code Here[/color]
Resume Next [color green]Æthis will tell the Program to continue on with the rest of the code. [/color]
End Sub
[/tt]

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.
[tt]
ErrorHandler:
[color green]ÆInclude Your Error Handling Code Here[/color]
MsgBox ôAn Error Occurredö & vbCrLf & _
ôError Number: ô & err.Number & vbCrLf & _
ôError Description: ô & err.Description, vbOkOnly, ôProgram Errorö
End Sub
[/tt]

Handled Errors
This is the best way to handle errors. If you know how to fix the given error then fix it.
[tt]
ErrorHandler:
[color green]ÆInclude Your Error Handling Code Here[/color]
Select Case err.Number
Case 90 [color green]ÆThis is a database Error[/color]
[color green]ÆCode to re-connect to database[/color]
Case Else
MsgBox ôAn Error Occurredö & vbCrLf & _
ôError Number: ô & err.Number & vbCrLf & _
ôError Description: ô & err.Description, vbOkOnly, ôProgram Errorö
End Select
End Sub
[/tt]

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.
[tt]
ErrorHandler:
[color green]ÆInclude Your Error Handling Code Here[/color]
Call GlogalErr(err.Number, err.Description, [color green] ÆAny additional Parameters.[/color])
End Sub

[color green]ÆMy Global Error handler for all error Handling[/color]
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
[/tt]

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.
[tt]
[color green]ÆPlace this code in each and every one of your code modules[/color]
Private Sub SampleCodeSub(ByVal PassedValue as String)
On Error GoTo ErrorHandler
Dim myName as String
[color green]ÆSet MyName equal to the name of the function or sub, and include any passed values[/color]
MyName = ôCommand1_Click( PassedValue=ö & PassedValue & ô)ö

[color green]ÆInclude the body of your program here[/color]

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

[color green]ÆPlace this code once in your main code module[/color]
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
[/tt]

And that my friends is error handling in a nutshell...
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top