📅  最后修改于: 2020-11-19 09:14:27             🧑  作者: Mango
编程中存在三种类型的错误:(a)语法错误,(b)运行时错误和(c)逻辑错误。
语法错误,也称为解析错误,发生在VBScript的解释时。例如,以下行由于缺少右括号而导致语法错误。
Function ErrorHanlding_Demo()
dim x,y
x = "Tutorialspoint"
y = Ucase(x
End Function
解释后,在执行期间会发生运行时错误,也称为异常。
例如,以下行会导致运行时错误,因为此处语法正确,但在运行时它将尝试调用fnmultiply,这是一个不存在的函数。
Function ErrorHanlding_Demo1()
Dim x,y
x = 10
y = 20
z = fnadd(x,y)
a = fnmultiply(x,y)
End Function
Function fnadd(x,y)
fnadd = x + y
End Function
逻辑错误是最难追踪的错误类型。这些错误不是语法或运行时错误的结果。相反,当您在驱动脚本的逻辑中犯了一个错误而没有得到预期的结果时,它们就会发生。
您无法捕获这些错误,因为这取决于您的业务需求,您希望在程序中放入哪种类型的逻辑。
例如,将数字除以零或编写的脚本进入无限循环。
假设我们遇到运行时错误,则通过显示错误消息来停止执行。作为开发人员,如果我们想捕获错误,则使用Error Object。
在下面的示例中, Err.Number提供错误编号,而Err.Description提供错误说明。
Err.Raise 6 ' Raise an overflow error.
MsgBox "Error # " & CStr(Err.Number) & " " & Err.Description
Err.Clear ' Clear the error.
VBA启用错误处理例程,也可以用于禁用错误处理例程。如果没有On Error语句,则发生的任何运行时错误都是致命的:显示错误消息,并且执行突然停止。
On Error { GoTo [ line | 0 | -1 ] | Resume Next }
Sr.No. | Keyword & Description |
---|---|
1 |
GoTo line Enables the error-handling routine that starts at the line specified in the required line argument. The specified line must be in the same procedure as the On Error statement, or a compile-time error will occur. |
2 |
GoTo 0 Disables the enabled error handler in the current procedure and resets it to Nothing. |
3 |
GoTo -1 Disables the enabled exception in the current procedure and resets it to Nothing. |
4 |
Resume Next Specifies that when a run-time error occurs, the control goes to the statement immediately following the statement where the error occurred, and the execution continues from that point. |
Public Sub OnErrorDemo()
On Error GoTo ErrorHandler ' Enable error-handling routine.
Dim x, y, z As Integer
x = 50
y = 0
z = x / y ' Divide by ZERO Error Raises
ErrorHandler: ' Error-handling routine.
Select Case Err.Number ' Evaluate error number.
Case 10 ' Divide by zero error
MsgBox ("You attempted to divide by zero!")
Case Else
MsgBox "UNKNOWN ERROR - Error# " & Err.Number & " : " & Err.Description
End Select
Resume Next
End Sub