Visual Basic/错误处理
样式
Visual Basic 中的错误处理,概述
- On Error Goto <Label>
- On Error Goto 0
- On Error Resume Next
- If Err.Number = 0
- If Err.Number <> 0
- Resume
- Resume <Label>
- Resume Next
- Err.Description
- Err.Raise <Number>
禁止错误并使用非零错误号检测错误:
Set MyCollection = New Collection
MyCollection.Add "Item", "Item"
On Error Resume Next
MyCollection.Add "Item", "Item" 'This result in an error
MyErrNumber = Err.Number
On Error Goto 0 'Restore the absence of error handling
If MyErrNumber <> 0 Then
'Error occurred
MsgBox "Item already present in the collection."
End If
创建错误处理程序:
Sub Test()
On Error Goto ErrorHandler
...
Exit Sub
ErrorHandler:
...
End Sub
创建区分每个错误号的错误处理程序:
Sub Test()
On Error Goto ErrorHandler
...
Exit Sub
ErrorHandler:
Select Case Err.Number
Case 0
'No error
Case 5
'...
Case Else
'...
End Select
End Sub
另请参阅 Visual Basic/Effective Programming#Errors_and_Exceptions 和 Visual Basic/Coding_Standards#Error_Handling。