2012年11月9日星期五

VB Script 中的 Try and Catch

VB Script 沒有 Try and Catch Exception 的處理,萬一遇到 Exception 怎麼辦?
原來有一個 Err 的 Object 可檢查有否出錯。


On Error Resume Next

DoStep1

If Err.Number <> 0 Then
  WScript.Echo "Error in DoStep1: " & Err.Description
  Err.Clear
End If

DoStep2

If Err.Number <> 0 Then
  WScript.Echo "Error in DoStop2:" & Err.Description
  Err.Clear
End If

'If you no longer want to continue following an error after that block's completed,
'call this.
On Error Goto 0





On Error Resume Next
Err.Clear
Set myObj = CreateObject("SomeKindOfClassThatDoesNotExist")
If Err.Number <> 0 Then
    WScript.Echo "Error: " & Err.Number
    WScript.Echo "Error (Hex): " & Hex(Err.Number)
    WScript.Echo "Source: " &  Err.Source
    WScript.Echo "Description: " &  Err.Description
    Err.Clear
End If
On Error Goto 0
WScript.Echo "This text will always print."

從網絡上找到應用的例子,總結來說就是用 On Error Resume Next 和 On Error Goto 0 來包著有可能出錯的 Statement,再檢查 Err.Number 來處理錯誤。
相比 Try - Catch Exception 就一定沒那麼好用,但也不失為 VBS 的解決方法。

來源 :
http://stackoverflow.com/questions/157747/vbscript-using-error-handling
http://stackoverflow.com/questions/4999364/try-catch-end-try-in-vbscript

沒有留言:

發佈留言