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。