Example: Complex error handling within a subroutine

The following example code shows a complicated error handler for a subroutine. When an error occurs, the code jumps to the
ErrHandler:
label. At this point the
Err.Number
property is used to format the error message. The code determines whether the subroutine is running in
FactoryTalk View Studio
or the
FactoryTalk View SE
Client.
  • If it is running in test run mode in
    FactoryTalk View Studio
    , a message is displayed presenting the option to debug the code and the subroutine jumps back to the line that caused the error.
  • If it is running in the
    FactoryTalk View SE
    Client, an error is logged to FactoryTalk Diagnostics on the
    FactoryTalk View SE
    Client.
Sub ExampleComplexErrorHandling() Dim oDisplay As DisplayClient.Display Dim sDispName As String ' Set the Error handler to jump to the ErrHandler: label on any error condition. On Error GoTo ErrHandler ' Set the display object to a display that is not loaded. ' In this example the string variable sDispName holds the display's name. sDispName = "Unknown Display" Set oDisplay = Application.LoadedDisplays(sDispName) ' Code may or may not reach the next line, depending on the actions taken in the error handler. oDisplay.SetFocus Exit Sub ErrHandler: Dim sErrMsg As String If Err.Number = gfxErrorConstants.gfxErrorCollectionIndex Then sErrMsg = "ExampleComplexErrorHandling():" & vbCrLf & "Display '" & sDispName & "' was not Found." Else sErrMsg = "ExampleComplexErrorHandling():" & vbCrLf & "Error Occurred: # " & Err.Number & ", " & Err.Description End If If Application.Name = "Graphics" Then ' Running in FactoryTalk View Studio If MsgBox(sErrMsg & vbCrLf & vbCrLf & "Do You Want to Debug?", vbYesNo Or vbQuestion) = vbYes Then ' if Yes was clicked, the following "Stop" statement stops the code Stop ' the F8 key is used from here to step through the code using ' the following "Resume" statement to return to the ' line that caused the error so the problem can be diagnosed and fixed. Resume End If Else ' Running in the SE Client (should not use MsgBox() call here) ' Here we use the replace command to change the formatting of the error message's CR-LF to a space. Application.LogDiagnosticMessage Replace(sErrMsg, vbCrLf, " "), ftDiagSeverityError ' Resume running on the next statement. Resume Next End If End Sub
Provide Feedback
Have questions or feedback about this documentation? Please submit your feedback here.
Normal