As you are writing your code, Visual Basic informs you of syntactical errors. However, once the program is running, you may encounter unexpected runtime errors in many circumstances.
For example, suppose you try to open a text file that the user has deleted. When a compiled program has an error like this, an error message is displayed and the program ends.
Although you cannot predict and write code for every possible type of error, "File Not Found" errors are fairly easy to handle. If you do not write code to work around the error, you can at least provide a message that makes more sense before ending the program.
The "On Error" Statement
The most common way to handle error conditions is to use Visual Basic's "On Error" statement. The "On Error" statement interrupts the normal flow of your program when an error occurs and begins executing your error handling code. A typical use is as follows :
On Error Goto FileOpenError
When this statement is executed, any errors that occur in subsequent statements cause Visual Basic to stop normal line-by-line execution and jump to the statement labeled as "FileOpenError".
Labeling Code Lines
Line labels in Visual Basic are similar to the line numbers of early BASIC. In Visual Basic, line labels can include text if you want, but each label must be unique. They are followed by a colon (:), as in the following example :
Private Sub Form_Load () On Error Goto FileOpenError Open "C:\SOMEFILE.TXT" For Unput As #1 Line Input #1, sData Exit Sub FileOpenError: MsgBox "There was a problem opening the file. Stop for coffee!" End End Sub
In the preceding sample code, if the "Open" or "Line Input" statements cause an error, the statements starting at the label "FileOpenError" are executed, causing the message to be displayed and ending the program.
You should note a few points about the sample code. First, note the location and style of the error handling routine. It is usually placed near the end of the subroutine, with the label not indented to indicate a special section of code.
Second, and more important, note the "Exit Sub" statement after the "Open" statement. It is necessary to prevent the error handler routine from executing even when the "Open" statement was successful.
Controlling Program Flow After an Error
In the preceding code example, you simply end the program if an error occurs. However, you can handle the error in several (better) ways :
- Exit the subroutine after informing the user of the error, and allow the program to continue running with limited functionality.
- Resume execution with the next statement following the error.
- Provide a way for the user to correct the error and retry the offending statement.
You can also have multiple labels within a procedure and set the current error handler multiple times. For example, you can add a line to the code sample after the "Open" statement that specifies a new label, "FileInputError". You can also turn off error handling with the following statement :
On Error Goto 0
The "On Error" statement goes hand in hand with the "Resume" statement. For example, this statement causes errors to be ignored and the program to proceed through each line of the code anyway :
On Error Resume Next
You should use the preceding line of code sparingly because it really just ignores errors rather than handles them. A better use of "Resume" is to go to another section of code. as in the following example :
Private Sub Form_Load () On Error Goto FileOpenError RetryHere: Open "C:\SOMEFILE.TXT" For Unput As #1 Line Input #1, sData Exit Sub FileOpenError: Dim sMessage As String sMessage = "There was a problem opening the file. " & VbCrLf sMessage = sMessage & "Press Retry to try again, or Cancel to quit." If MsgBox (sMessage, vbRetryCancel + vbCritical, "Error!") = vbRetry Then Resume RetryHere Else End End If End Sub
You can though use "On Error Resume Next" if you are trying to connect to AutoCAD from an external Visual Basic or other application :
'if error carry on with next line On Error Resume Next 'set reference to AutoCAD Application Set acadApp = GetObject(, "AutoCAD.Application.16") 'if there is an error (AutoCAD not open) If Err Then 'clear the error Err.Clear 'open AutoCAD Set acadApp = CreateObject("Autocad.Application.16") 'setq reference to AutoCAD Application Set acadApp = GetObject(, "AutoCAD.Application.16") 'if there is another error If Err Then 'inform user MsgBox Err.Description 'exit application Exit Sub End If End If
Next, set the document variable to the Document object in the AutoCAD application. The Document object is returned by the ActiveDocument property of the Application object :
Dim ThisDrawing as AcadDocument Set ThisDrawing = acadApp.ActiveDocument
From this point on, use the "ThisDrawing" variable to reference the current AutoCAD drawing just like AutoCAD VBA.
Determining The Type of Error
After an error has occurred, your code can find out more information about the error in several ways :
- Err - Contains a number that represents the error.
- Error - Contains a string describing the error.
- Err Object - Contains error number, description and additional information. Also used to raise your own custom errors.
If you know how to recover from certain errors that may occur, you can use these objects to respond intelligently to a specific error. In one of the previous examples, you received a "File Not Found" error, which is number 53. You can easily add code in the error handler to take appropriate action (that is, check another file) if the value of "Err" is 53.
Hint : When you are writing an error handling routine with a message box, display the error number and description in your message box to make troubleshooting easier.