示例:子程序中复杂的错误处理

下面的示例代码显示了一个子程序的复杂错误处理程序。发生错误时,代码将跳转至
ErrHandler:
标记。此时,使用
Err.Number
属性来指定错误消息格式。代码会确定子程序将在
FactoryTalk View Studio
中还是
FactoryTalk View SE
Client 中运行。
  • 如果将在
    FactoryTalk View Studio
    中以测试运行模式运行子程序,则会显示一条给出代码调试选项的消息,子程序会跳转回发生错误的行。
  • 如果将在
    FactoryTalk View SE
    Client 中运行子程序,则会将错误记录到
    FactoryTalk View SE
    Client 的 FactoryTalk Diagnostics 中。
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
提供反馈
对本文档有问题或反馈吗? 请在这里提交您的反馈
Normal