This section provides a tutorial example on how to use 'On Error GoTo 0' to turn off the error handling flag in a procedure to catch the first runtime error.
As you can see from the previous section, my last VBScript example reported the last runtime error,
not the first one.
If you want to catch the first runtime error is a large section of code,
you need to:
Enter the "On Error Resume Next" statement in the main code to turn on the error handling flag for the main code.
Put that section of code into a new subroutine procedure.
Enter the "On Error Goto 0" statement in the new procedure to turn off the error handling flag for that procedure.
Check the Err.Number property right after calling that procedure.
Here is the modified VBScript example to catch the first runtime error in a section of code:
<html>
<body>
<!-- runtime_error_caught.html
- Copyright (c) 2015, HerongYang.com, All Rights Reserved.
-->
<pre>
<script language="vbscript">
On Error Resume Next ' Turn on the error handling flag
Call CheckError()
Call CodeToBeMonitored()
Call CheckError()
Sub CodeToBeMonitored()
On Error Goto 0 ' Turn off the error handling flag
' Exit on the first runtime error
document.writeln("")
document.writeln("Before statement: x = 1/0")
x = 1/0 ' Division by zero
document.writeln("Before statement: y = CInt(777777)")
y = CInt(777777) ' Overflow
document.writeln("Before statement: z = 1 + ""2nd""")
z = 1 + "2nd" ' Type mismatch
document.writeln("End of test")
End Sub
Sub CheckError()
document.writeln()
If Err.Number > 0 Then
document.writeln("A runtime error has occurred:")
document.writeln(" Err.Number = " & Err.Number)
document.writeln(" Err.Description = " & Err.Description)
document.writeln(" Err.Source = " & Err.Source)
Else
document.writeln("There is no error at this time.")
End If
End Sub
</script>
</pre>
</body>
</html>
Run this modified example code in IE, you will get:
There is no error at this time.
Before statement: x = 1/0
A runtime error has occurred:
Err.Number = 11
Err.Description = Division by zero
Err.Source = Microsoft VBScript runtime error
What heppened was:
When the first runtime error occurred on statement, x = 1/0, in the CodeToBeMonitored() procedure,
execution stopped for that procedure, because the error handling flag was turned off for that procedure.
Execution control was transferred back to the main code with the runtime error.
Back in the main code, the execution continued because the error handling flag was turned on
for the main code.
When CheckError() was called at the end, Err.Number is 11, indicating that the runtime error
occurred was a "Division by zero" error.
Now this example code behaves similar to "try ... catch" statement in some other language.