我想使用VBScript来捕获错误并记录它们(即错误"记录某些内容")然后恢复脚本的下一行.
例如,
On Error Resume Next 'Do Step 1 'Do Step 2 'Do Step 3
当在步骤1发生错误时,我希望它记录该错误(或用它执行其他自定义功能),然后在步骤2恢复.这可能吗?我该如何实现它?
编辑:我可以这样做吗?
On Error Resume myErrCatch 'Do step 1 'Do step 2 'Do step 3 myErrCatch: 'log error Resume Next
Dylan Beatti.. 152
VBScript没有抛出或捕获异常的概念,但运行时提供了一个全局Err对象,其中包含上次执行的操作的结果.您必须在每次操作后显式检查Err.Number属性是否为非零.
On Error Resume Next DoStep1 If Err.Number <> 0 Then WScript.Echo "Error in DoStep1: " & Err.Description Err.Clear End If DoStep2 If Err.Number <> 0 Then WScript.Echo "Error in DoStop2:" & Err.Description Err.Clear End If 'If you no longer want to continue following an error after that block's completed, 'call this. On Error Goto 0
Visual Basic和Visual Basic for Applications(VBA)支持"On Error Goto [label]"语法,但VBScript不支持此语言功能,因此您必须使用On Error Resume Next,如上所述.
VBScript没有抛出或捕获异常的概念,但运行时提供了一个全局Err对象,其中包含上次执行的操作的结果.您必须在每次操作后显式检查Err.Number属性是否为非零.
On Error Resume Next DoStep1 If Err.Number <> 0 Then WScript.Echo "Error in DoStep1: " & Err.Description Err.Clear End If DoStep2 If Err.Number <> 0 Then WScript.Echo "Error in DoStop2:" & Err.Description Err.Clear End If 'If you no longer want to continue following an error after that block's completed, 'call this. On Error Goto 0
Visual Basic和Visual Basic for Applications(VBA)支持"On Error Goto [label]"语法,但VBScript不支持此语言功能,因此您必须使用On Error Resume Next,如上所述.
请注意,On Error Resume Next
未全局设置.您可以将不安全的代码部分放入函数中,如果发生错误将立即中断,并从包含先前OERN
语句的子函数中调用此函数.
ErrCatch() Sub ErrCatch() Dim Res, CurrentStep On Error Resume Next Res = UnSafeCode(20, CurrentStep) MsgBox "ErrStep " & CurrentStep & vbCrLf & Err.Description End Sub Function UnSafeCode(Arg, ErrStep) ErrStep = 1 UnSafeCode = 1 / (Arg - 10) ErrStep = 2 UnSafeCode = 1 / (Arg - 20) ErrStep = 3 UnSafeCode = 1 / (Arg - 30) ErrStep = 0 End Function