VB6 beginners tutorial - Learn VB6

Advanced VB6 tutorial - Learn Advanced VB6

Systems Analysis - System analysis and Design tutorial for Software Engineering

You are here: Visual Basic > Advanced VB6 tutorial > Chapter 11

Handling Errors in Code - Inline Error Handling

Not all error handling occurs at the end of a procedure, and you are not limited to one On Error statement in each sub-routine or function you code. Sometimes the error-handling requirements change from the beginning of a routine to the end of a routine. There may be some sections of your code where you expect errors to occur— and don't care—and there are other lines where you do not expect errors and want to be warned when they occur.

You may have a procedure that reads information from a file, for example, does some processing, and exits. If the file is not found, you want to exit the routine. If any other error occurs, you want to display a message box. Your code could look something like this:

Private SubA()
' set the initial error handling to go to line SubA_Exit
On Error Goto SubA_Exit

Dim sFile as String
sFile = "filename.dat"

' do some additional processing
' Reset the error handling to go to line SubA_Exit
' for the Open statement.

On Error Goto SubA_Exit
Open sFile For Input As #1

' Reset to original error handling
On Error Goto SubA_Error
' continue processing...

Exit Sub

' error handling

End Sub

In this example, the On Error statement is used three times. First at the beginning of the sub-routine, the On Error statement is used to tell Visual Basic to go to the error-handling code at SubA_Error when an error occurs. Then before the Open statement, On Error is used again to say that if any error occurs to go to line SubA_Exit and then to leave the routine. Finally the On Error statement is used again to send errors to the SubA_Error line after the Open statement has run successfully.

The number of On Error statements in a procedure is only constrained by the limit on total lines and bytes of code for Visual Basic procedures. In addition, you can use any of the On Error types in the same procedure. You can use the Resume, Resume Next, Goto <line>, and Goto 0 all in the same procedure, and each can be used several times to toggle between different types of error handling.


<< Previous | Contents | Next >>

Home | About Us | Privacy Policy | Contact Us

Copyright © | All Rights Reserved