"函式實現除法操作並返回結果。如果發生錯誤(如0除)返回值為0Public Function Divide(Byval v as Single) As Single "為了消除可能的錯誤(如即0除錯誤)開啟錯誤捕獲陷阱 "一旦發生錯誤,立即轉到行標號ErrProc執行 On Error Goto ErrProc Divide = 1 / v Exit Function ErrProc: "發生錯誤時轉到這裡處理 "清除錯誤 Err.Clear Divide = 0 End Function
更為簡潔的寫法如下:
"函式實現除法操作並返回結果。如果發生錯誤(如0除)返回值為0Public Function Divide(Byval v as Single) As Single Divide = 0 "為了消除可能的錯誤(如即0除錯誤)開啟錯誤捕獲陷阱 "當錯誤發生時,立即執行下一條語句,即 On Error Goto 0 On Error Resume Next Divide = 1 / v "關閉錯誤陷阱 On Error Goto 0End Function
用On Error 捕獲程式執行時引發的錯誤,捕獲後清除錯誤。實現方法如下
"函式實現除法操作並返回結果。如果發生錯誤(如0除)返回值為0Public Function Divide(Byval v as Single) As Single "為了消除可能的錯誤(如即0除錯誤)開啟錯誤捕獲陷阱 "一旦發生錯誤,立即轉到行標號ErrProc執行 On Error Goto ErrProc Divide = 1 / v Exit Function ErrProc: "發生錯誤時轉到這裡處理 "清除錯誤 Err.Clear Divide = 0 End Function
更為簡潔的寫法如下:
"函式實現除法操作並返回結果。如果發生錯誤(如0除)返回值為0Public Function Divide(Byval v as Single) As Single Divide = 0 "為了消除可能的錯誤(如即0除錯誤)開啟錯誤捕獲陷阱 "當錯誤發生時,立即執行下一條語句,即 On Error Goto 0 On Error Resume Next Divide = 1 / v "關閉錯誤陷阱 On Error Goto 0End Function