I want to use VBScript to catch errors and log them (ie on error "log something") then resume the next line of the script.
For example,
On Error Resume Next 'Do Step 1 'Do Step 2 'Do Step 3
When an error occurs on step 1, I want it to log that error (or perform other custom functions with it) then resume at step 2. Is this possible? and how can I implement it?
EDIT: Can I do something like this?
On Error Resume myErrCatch 'Do step 1 'Do step 2 'Do step 3 myErrCatch: 'log error Resume Next
There are three types of errors in programming: (a) Syntax Errors, (b) Runtime Errors, and (c) Logical Errors.
An On Error Resume Next statement becomes inactive if another procedure is called, so you should execute an On Error Resume Next statement in each called routine if you want inline error handling within that routine. The VBScript Err object can be used for detecting the error and its description.
The properties of the Err object are set by the generator of an error — Visual Basic, an Automation object, or the VBScript programmer. The default property of the Err object is Number. Err. Number contains an integer and can be used by an Automation object to return an SCODE.
D - None of the above. Q 39 - Which of the following is used to capture a runtime Error in VBScript? A - Err object.
VBScript has no notion of throwing or catching exceptions, but the runtime provides a global Err object that contains the results of the last operation performed. You have to explicitly check whether the Err.Number property is non-zero after each operation.
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
The "On Error Goto [label]" syntax is supported by Visual Basic and Visual Basic for Applications (VBA), but VBScript doesn't support this language feature so you have to use On Error Resume Next as described above.
Note that On Error Resume Next
is not set globally. You can put your unsafe part of code eg into a function, which will interrupted immediately if error occurs, and call this function from sub containing precedent OERN
statement.
ErrCatch() Sub ErrCatch() Dim Res, CurrentStep On Error Resume Next Res = UnSafeCode(20, CurrentStep) MsgBox "ErrStep " & CurrentStep & vbCrLf & Err.Description End Sub Function UnSafeCode(Arg, ErrStep) ErrStep = 1 UnSafeCode = 1 / (Arg - 10) ErrStep = 2 UnSafeCode = 1 / (Arg - 20) ErrStep = 3 UnSafeCode = 1 / (Arg - 30) ErrStep = 0 End Function
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With