圖7-16 錯誤處理過程
這種錯誤調用鏈意味著可以建立防止使程式停止啟動並執行運行期錯誤的函數和子程式。如果在子程式的開頭放置一個On Error Resume Next語句,任何運行期錯誤會中止這個子程式的運行,但是調用該子程式的程式將繼續運行而不會引起網頁的停止。
例如,如果需要向一個檔案中寫入字串,可以通過一個獨立的函數對檔案進行訪問檔案,防止錯誤中斷整個程式的運行:
' create a file named strFileName, overwriting any existing one with that name
' and writes strContent into it then closes the file
' returns True if it succeeds, or False on any error
Function WriteNewFile(strFileName, strContent)
On Error Resume Next ' turn off the default error handler
WiteNewFile = Flase ' default return value of function
Set objFSO = CreateObject("Scripting.FileSystemObject")
If Err.Number = 0 Then Set objFile = objFSO.CreateTextFile(strFileName, True)
If Err.Number = 0 Then objFile.WriteLine strContent
If Err.Number = 0 Then objFile.Close
If Err.Number = 0 Then WriteNewFile = True
End Function
注意上面的程式在試圖處理每個程式語句之前,先檢查VBScript的Err對象的Number屬性。如果這個值為0(還沒有出現錯誤),那麼就能夠繼續對檔案的定入和建立過程。然而如果錯誤確實發生了,指令碼引擎將設定Err對象的屬性的值,並且繼續處理下一行。
只要不引起錯誤而能正常運行,函數的傳回值將設定為“True”。否則函數將返回“False”。在編程中可以在對其進行測試以後,再使用該函數和採取其他行動。