Intrinsic Ctrls
ActiveX Ctrls
Cmd Reference
File Handling

Drag and Drop
Error Handling
Database Controls

Internet File Transfers
Perl Commands
Web Page Forms

GBIC >> VB >> Tutorials >> Error Handling
Error Handling
The bottom line is that all of us make mistakes. VB is pretty clever about finding syntax errors within the IDE, but a number of the possible errors simply cannot be discovered until you try to run the program. This section discusses some of the available error detection and correction techniques.

Users Hate Errors!

If you make an error in VB, and you haven't written the code needed to respond to the error, do you know what happens? Well, VB simply puts up a message box saying there was an error. If you click on the OK button in the message then the VB program shuts down without saving anything that your user might have typed in. Let's be perfectly clear - This is not good! Your users will not like it and they will tell you about it.

It's amazingly hard for a programmer to figure out how a user will mis-use the program. Actually, the term "mis-use" is not correct because the user will simply do whatever the application allows him to do. If the programmer didn't anticipate a particular input that can crash the program or if the programmer didn't anticipate a particular combination of entries that could also crash the program, then shame on the programmer!

At a minimum, the programmer must allow for the possibility of an unknown error occurring and providing a means within the code to respond to the error, giving the user options to save (or not) any data already entered.

Contrary to the contempt some programmers have for non-technical users, it is not acceptable practice to release programs which lose the user's data if he doesn't follow the user's manual. This is especially true because often a user's manual is ambigous, or written in techno-speak which the user might not understand.

It's also not acceptable to include in the user's manual an instruction that says "Don't do this or the program will fail!". If the programmer knows of an input that will crash the program, it's his responsibility to add the code to take care of the possible error condition.

In case you don't catch my drift here's my philosophy in a nutshell - It's the programmer's job to create a program which can respond to any possible user input without crashing and losing the user's data. You can whine all day long about how unskilled the users are, but you might as well accept that some user somewhere will get careless and make a weird combination of inputs that you didn't foresee. Under those conditions it is your job to protect the user from his own actions. Fortunately, VB has the features which let you provide this level of protection.

When you make an error in VB, such as a divide by zero, VB responds by stopping execution of the program and will look for instructions in the code on what to do next. If you don't include those instructions, the program will simply shut down. As I've said - This is not good!

To respond to errors, VB provides the following code which turns on its error correction options:

On Error GoTo LabelX
What this means is that if an error occurs, then the program will resume execution at the line which is labelled "LabelX". Of course, you can use your own label name to identify where execution will begin.

In case you don't remember, a label is a short word/phrase which ends in a colon character, such as "BeginHere:". Any line can have a label. It goes at the start of the line and does not interfere with any additional code on that line.

One thing to remember is that the On Error statement only turns on error trapping for the procedure (Sub or Function) in which the code is found. You must use the On Error statement in every Sub/Function for which you want error trapping to occur.

Here's a very sample bit of code to explain how error trapping works:

Sub TestProcedure()
  On Error GoTo Label5
  Value = 10 / BottomNumber
  Exit Sub
  If BottomNumber = 0 Then BottomNumber = 1
End Sub
In this example, the On Error statement tells VB that if an error occurs, begin executing the code which starts at the line labelled "Label5". In that code (for this example), if BottomNumber is 0, an error will occur and execution starts with the "If" statement. That statement will set the denominator to 1 if it was zero. The "Resume" statement will tell VB to shift execution to the same line which gave the error in the first place! Now that the denominator is changed, no error occurs and the Exit Sub procedure will execute next.

There are some nuances to take notice of in this example:

The use of the statement "Resume" can take 3 forms:

  • Resume
    When VB hits a Resume statement in the error code, it will move execution to the same line which caused the error, attempting to re-execute the line again. Be careful here, because for this to work, your error code must have fixed the problem that caused the error.
  • Resume Next
    When VB hits a "Resume Next" statement in the error code, it will move execution to the line following the line of code which caused the error. This is usually done when the error code does not, or cannot, correct the problem.
  • Resume LabelX
    In this case, VB is directed to a specific line within the current procedure. It can any line you chose, usually chosen based on the specific error that occurred. Generally, this approach is frowned on because it makes the code a little less readable, but if it fits your needs then I wouldn't hesitate to use it.

Like an "Exit For" or an "Exit Do" statement, your code can direct VB to leave a procedure at any time. In the example above, the "Exit Sub" is used to leave the Sub procedure before the code following the line "Label5" is executed. This is a very typical way of preventing the error code from being executed.

If you want your application to take no action at all when an error occurs then you simply don't put any code behind the error label. In those cases, an "Exit Sub" is not necessary because the "End Sub" will give the same result.

Err Object
To help out programmers, VB6 now provides a built-in object called "Err". On occurrence of an error, VB fills the properties of the Err object with information that uniquely identifies the error and with information that you can use in your code to figure out what actions to take as a result of the error. A bit further in this tutorial, I list the complete list of the Err object's properties and methods. It has no events.

The Err object's properties are reset to zero or zero-length strings ("") after an Exit Sub, Exit Function, Exit Property or Resume Next statement within an error-handling routine. Using any form of the Resume statement outside of an error-handling routine will not reset the Err object's properties. The Clear method can be used to explicitly reset Err.

The Err object is a recent VB feature. In older versions the Error statement was available (still is, for backward compatibility) and was used to have VB simulate an error. The Err.Raise method is now the preferred approach.

For test purposes, you can even cause VB to simulate an error. To do so, use the Raise method as described below.

The full list of Err object properties is:

  • Description
  • HelpContext
  • HelpFile
  • LastDLLError
  • Number
  • Source

And, it's methods are:

  • Clear
    Provides an immediate clearing of all Err object properties. Strings are set to null and numeric values are set to zero. You might choose to use it following the use of the statement "On Error Resume Next" since the error information would no longer apply

    The Clear method is called automatically whenever any of the following statements is executed:

    • Any type of Resume statement
    • Exit Sub, Exit Function, Exit Property
    • Any On Error statement

    The value in clearing the Err properties is to make sure that any code which depends on those properties doesn't see information from a previous error which has already be responded to by code.

  • Raise

    Error Handling Heirarchy
    Last, but not least in this tutorial, is the discussion on error handling heirarchy. You should be aware that the code of a procedure might call a second procedure, which in turn can call even a third procedure. The question is how are errors handled in the second or third procedures?

    If, in a procedure, an On Error statement is executed, then that error handler (the code at the error handling label) is considered to be "enabled". If the On Error statement is executed then when an error occurs, the error handler in that procedure is executed.

    In a situation when a chain of called procedures exists (i.e., Procedure One calls Procedure Two which calls Procedure Three), then when an error occurs VB will move up the chain of procedures looking for the first enabled error handler it can find. If no enabled error handler exists, VB will give an error message and terminate the program (remember, this is bad!).

    IDE Debugging Tools
    All of the discussion so far focused on how to handle errors in an application while the program was running. The VB IDE has some very clever tools which help you track down the source of the error. I don't go over these in this tutorial but I point them out and suggest you learn to use them in your own projects.

    • Breakpoints
      Easily the most common method of debugging code. When a line of code is selected as a breakpoint, the program stops temporarily without losing the values of variables. Once stopped, you can check/change values or even re-write code as needed and then restart the program using those changes.
    • Step Into/Over/Out
      A close second, the Step options are valuable because it gives you the ability to bypass blocks of code which you know to be good.
    • Windows - Local/Immediate/Watch
      Provides a more sophisticated way to monitor specific variables and to take action based on the state/value of those variables.
    • Single Line Execution
      Once you have stopped a VB program, you can execute the code one line at a time with this feature. It's a very methodical way to move through your program and confirm that any logic/redirection code works as intended.

    Bottom Line
    Put error handling code in any application which you distribute to users. For your own purposes you can choose to do without it but don't expect your users to pay the price of your decision to deny them protection from errors. The VB IDE has some excellent tools to help you analyze and debug code. You can prevent spending hours of time searching for errors simply by understanding and using the built-in IDE capabilities.