我正在尝试修改 vbscript 并将其转换为 Powershell。我的函数 SearchAD 上有一段代码块,带有 On Error。
on error resume next
Set objRS = command.execute
SearchAD = objRS.RecordCount
on error goto 0
Run Code Online (Sandbox Code Playgroud)
我的问题是代码的哪一部分可以触发 RESUME Next,哪一部分用于 GOTO 0。
在 VBScript 中有两种错误状态(在其他 VB 中为三种)。
On Error Goto 0
Run Code Online (Sandbox Code Playgroud)
vbscript 处理错误。您的程序因错误而崩溃。
On Error Resume Next
Run Code Online (Sandbox Code Playgroud)
VBScript 设置 err 对象但不引发错误。您需要在可能引发错误的每一行之后放置
If err.number <> 0 then
FreakoutAndFixTheError
err.clear
wscript.quit 'if you can't fix
End If
Run Code Online (Sandbox Code Playgroud)
在 VB6 和 VBA 中也有
On Error Goto LineNumber (or a label)
Run Code Online (Sandbox Code Playgroud)
简而言之,On Error Resume Next禁用错误报告。并On Error GoTo 0恢复它。当程序员预计会发生错误但不希望该错误未得到处理并停止其脚本时,通常会使用它。例如:
' This statement will cause VBScript to throw an error and halt.
i = 1 / 0
' Instead, let us handle the error and decide if its important...
On Error Resume Next ' Turn off error reporting
i = 1 / 0
' Now, we can test the Err object to see if any errors were thrown...
If Err.Number = 0 Then
' Success. No error occurred.
ElseIf Err.Number = 11 Then
' Error #11 is 'Division by zero'. Do we want to allow it?
End If
' We're through the risky section. Restore error reporting.
On Error GoTo 0
Run Code Online (Sandbox Code Playgroud)
现在是肥皂盒咆哮的时候了。不要使用它。几乎总是有比使用更好的方法On Error Resume Next。断言变量值。在尝试访问数组元素之前检查数组边界。进行质量检查测试。验证用户输入。成为一名优秀的程序员并涵盖所有角度。不要对任何错误视而不见,并假设一切都会正常。它经常被 VB 初学者滥用,不幸的是,甚至一些专家也滥用它!(吐槽结束)