Handling Runtime Errors

Runtime errors occur as your macro runs, and typically result from specific conditions present at that time. For example, if you prompt the user for a host name, and attempt to connect to that host, but the host is not available, the Connect method fails and Visual Basic generates a runtime error.

You should always include some form of error handling in your macros to deal with runtime errors. Without any error handling, a runtime error causes a macro to stop immediately, and gives the user little information.

To deal with runtime errors, you'll need to trap (catch) the errors, handle them, and then resume execution after the error is handled:

Trapping Runtime Errors

Handling Errors Inline

Using Error Handling Routines

Error Codes

Two other types of errors you may encounter as you program in Reflection include:
  • Compiler errors which prevent your macros from running, and typically result from errors in syntax.
  • Programming logic, which occurs when your macro does not function as expected — the programming syntax is correct, the macro compiles, but an error in logic causes the macro to produce unexpected or incorrect results. Use the debugging tools in the Visual Basic Editor to track down logic errors. (Search for debugging code in the Visual Basic Editor Help index for more information.)
Most of the illustrative examples in this guide do not include error handling because these samples are intended to show how to perform specific tasks or illustrate concepts. If you use these samples as part of your production macro, be sure to add error handling routines.
To determine the meaning of specific error codes, see Error Codes.


Trapping Runtime Errors

The first step in dealing with runtime errors is to set a "trap" to catch the error. You do this by including an On Error statement in your macro. When a runtime error occurs, the On Error statement transfers control to an error-handling routine.

To trap errors, you must set your error trap above the point in the procedure where errors are likely to occur. A good practice is to place the error trap near the top of the procedure. To avoid having the error-handling routine execute even when no error occurs, you should include an Exit Sub or Exit Function statement just before the error-handling routine's label.

Trapping errors
Copy Code
Sub ErrorDemo ()
  On Error GoTo MyHandler
  'Program code goes here. To avoid invoking the error handling routine after this
  'section is executed, include the following line just above the error-handler.
  Exit Sub

  'Error is handled and the macro terminates gracefully.
  Exit Sub
End Sub

Resuming a Procedure After an Error

After your macro successfully traps and handles an error, you can choose whether to have the macro exit the procedure (by including an Exit Sub or Exit Function statement in the handler) or resume the procedure (by including a resume statement). When you resume a procedure, you can also have the macro correct the error condition automatically, in which case the end user may never know that an error occurred.

Use this statement

To do this


Exit the error handler and resume the macro at the line that caused the error. Your macro must automatically correct the error condition or prompt the user to correct it before resuming; otherwise, the error will occur again.

Resume Next

Resume the macro at the line following the one that caused the error.

Resume Label

Exit the error handler and pass control to the statement identified by the label.

Each of the following examples show the general structure of a procedure that includes an error trap and error-handling routine.

In this example, control resumes at the line following the statement that caused the runtime error.

Resuming control on line after error
Copy Code
Sub SampleResumeNext ()
  On Error GoTo MyHandler
  'Normal program code goes here. If an error
  'occurs, control is transferred to the handler.
  'When the handler is done, control resumes
  'at the next line here.
  Exit Sub

  'Error is handled, and control resumes at the line
  'after the statement that caused the error.
  Resume Next
End Sub


 In this example, control returns to the DoPrompt label after the error handler executes.

Resuming control at label 
Copy Code
Sub SampleResumeToLabel ()
  On Error GoTo MyHandler
  'Normal program code goes here. If an error occurs,
  'control is transferred to the handler.
  Exit Sub

  'Error is handled, and then control is transferred
  'to the DoPrompt label.
  Resume DoPrompt
End Sub

Handling Errors Inline

To cause a procedure to handle relatively simple runtime errors without branching to a separate error-handling routine, you can use a form of the On Error statement that lets you deal with errors inline; that is, directly in the code that caused the error, rather than in a separate routine.

To handle an error inline, use the Resume Next statement with On Error. Any errors that occur during runtime cause Reflection to continue executing the macro at the next statement. If an error occurs, it is handled by opening a dialog box, passing control to another procedure or to a routine within the same procedure.

This example checks for errors when saving an IBM 3270 or 5250 session document. If the save operation fails, an error message appears. If the save operation succeeds (Err.Number returns 0), a "Save complete" message appears.

Handling an error inline
Copy Code
Sub SaveSessionDemo()
  Dim theError As Integer
  On Error Resume Next
  theError = Err.Number

  Select Case theError
    Case 0
     MsgBox "Save complete."
    Case Else
     MsgBox Err.Description & "."
  End Select
End Sub

Using Error Handling Routines

After you set an error trap, write the error-handling routine that will deal with errors that are likely to occur — in addition to unanticipated errors — when your macro runs. You can identify an error-handling routine by its line label.

Observe the following guidelines:

  • Place error-handling routines near the end of the procedure, just before the End Sub or End Function statement.
  • Avoid executing error-handling code when no error occurs by placing an Exit Sub or Exit Function statement just before the error handler's label. A Resume statement is typically used to continue execution of the macro after the error handler is done.
  • Use the Err object to return specific information about the error. (See the Visual Basic Help for more information about the Err object.)

The following samples show a simple error handling routine and a more rigorous routine for handling errors related to file access.

This simple error handler displays a custom error message and then terminates the macro:

Terminating the macro on error
Copy Code
Sub ExitOnError ()
  On Error GoTo MyHandler
  'Main body of procedure.
  Exit Sub

   MsgBox "Error occurred. Cannot complete operation."
  Exit Sub
End Sub


The following macro uses the OpenFileNameDialog function to open a File Open dialog box and request a file, and then tries to write to that file. If the file is read-only, the error handler (using the Err object) displays a "Path/File access error" with an error code of 75, and returns the user to the File Open dialog box. 

Using the Err object
Copy Code
  lStructSize As Long
  hwndOwner As Long
  hInstance As Long
  lpstrFilter As String
  lpstrCustomFilter As String
  nMaxCustFilter As Long
  nFilterIndex As Long
  lpstrFile As String
  nMaxFile As Long
  lpstrFileTitle As String
  nMaxFileTitle As Long
  lpstrInitialDir As String
  lpstrTitle As String
  Flags As Long
  nFileOffset As Integer
  nFileExtension As Integer
  lpstrDefExt As String
  lCustData As Long
  lpfnHook As Long
  lpTemplateName As String
End Type

Declare Function GetOpenFilename _
  Lib "COMDLG32.DLL" Alias "GetOpenFileNameA" (pOpenfilename As OPENFILENAME) As Long

Function OpenFileNameDialog() As String
  Dim fileName As String
  With OFN
    'Size of structure.
    .lStructSize = Len(OFN)
    'Size of buffer.
    .nMaxFile = 260
    'Create buffer.
    .lpstrFile = String(.nMaxFile - 1, 0)
    'Call function.
    Ret = GetOpenFilename(OFN)
    'Non-zero is success.
    If Ret <> 0 Then
      'Find first null char.
      n = InStr(.lpstrFile, vbNullChar)
      'Return what's before it.
      fileName = Mid(.lpstrFile, 1, n - 1)
      OpenFileNameDialog = .lpstrFile
    End If
  End With
End Function

Sub WriteToFile()
  Dim fileName As String
  On Error GoTo MyHandler
  fileName = OpenFileNameDialog()
  Open fileName For Append As #1
  Write #1, "stuff"
  Close #1
  Exit Sub
  'If the file is read-only, let the user try again.
  'The underscore character is used here to break the long line.
  If Err.Number = 75 Then
    MsgBox "Can't write to file" & fileName & _
    ". Please choose another.", , "File Error"
    Resume chooseAgain
    'For other errors display the error message, close the
    'open file and exit.
    MsgBox Err.Number & ": " & Err.Description, , "File Error"
    Close #1
    Exit Sub
  End If
End Sub

Note: If you have existing Reflection Basic error-handling code that was written without using the Err object, you can use it in Visual Basic without rewriting it. (The default property of the Err object is Number.) Because the default property can be represented by the object name Err, earlier code written using the Err function or Err statement doesn't have to be modified.

Error Codes

Errors that occur when you run your macros can be generated by Visual Basic or Reflection commands. The values for error codes specific to Reflection vary, depending on which host you use.

These error codes

May occur when executing

1 - 1000

A Visual Basic command.

(For information about these errors, see "trappable errors" in the Microsoft Visual Basic Help.)

4000 - 4999

A Reflection command supported by IBM hosts (3270 and 5250).

These errors are represented by error constants that begin with "rcRte". For example, the predefined constant rcRtePathNotFound is equivalent to 4023.

For a list of these error codes, see Error Codes for IBM Terminals.

10,000 - 10,999

A Reflection command supported by OpenSystems hosts (UNIX and OpenVMS, and ReGIS Graphics).

These errors are represented by error constants beginning with "rcErr". For example, the predefined constant rcErrNotConnected is equivalent to 10,023.

For a list of these error codes, see Error Codes for VT Terminals.








2015 Attachmate