一個轉到錯誤處理程序是一個程序的頂部是良好的編程風格,應該是錯誤的處理對於大多數程序的最低金額。但是,它比檢查可能導致錯誤的代碼行之後的錯誤更不靈活。當在相當簡單的過程中添加錯誤處理時,我使用On Error GoTo ...語句和例程底部的catch-all錯誤處理程序。
On Error GoTo procErrorHandler
If Not Exists(BaseDirectory + "\ARCHIVE") Then
MkDir BaseDirectory + "\ARCHIVE"
End If
intvalue1 = 12
intvalue2 = 0
intvalue3 = intvalue1/intvalue
ProcExit:
Exit Sub
procErrorHandler:
Call MsgBox("There was an error in the procedure. Error " & CStr(Err.Number) & ", " & Err.Description, vbExclamation, App.Title)
Resume ProcExit ' A chance to do any cleanup needed
我不是多轉到語句的粉絲,因爲它使代碼難以閱讀和遵守。在我正在執行幾個步驟的過程中,我想返回一個更準確地描述代碼出錯的位置的錯誤,或者在可能有機會從錯誤中恢復並繼續的情況下,我禁用全部錯誤處理類型並在關鍵步驟後檢查Err.Number屬性。如果我修改Matt的錯誤處理,我會以這種方式編寫程序。
On Error Resume Next
If Not Exists(BaseDirectory + "\ARCHIVE") Then
MkDir BaseDirectory + "\ARCHIVE"
End If
' check for errors making the directory
If Err.Number <> 0 Then
Call MsgBox("Error making directory - " & Err.Number & vbCrLf & Err.Description, vbExclamation, App.Title)
End If
intvalue1 = 12
intvalue2 = 0
intvalue3 = intvalue1/intvalue
' check for errors getting intvalue3
If Err.Number <> 0 Then
Call MsgBox("Error doing arithmetic - " & Err.Number & vbCrLf & Err.Description, vbExclamation, App.Title)
End If
Exit Sub
來源
2012-01-27 18:02:03
jac
感謝您的解釋! – JimDel 2012-01-27 16:47:39
+1。該文件解釋這很清楚... ... http://msdn.microsoft.com/en-us/library/aa266173(v=vs.60).aspx – MarkJ 2012-01-27 16:53:09
錯誤 - 除零除只處理如果MkDir操作不會拋出錯誤 – 2012-01-27 16:58:22