Discussion:
Thoughts on current error handling best practice with VBScript
(too old to reply)
FUBARinSFO
2008-02-02 01:51:56 UTC
Permalink
Hi:

While confused that I wasn't getting runtiime error messages when I
tried to write to files with invalid paths, I poked around see that
error handling is generally absent in vbscript. Since I make so few
errors in my programs, this has never been an issue for me....not.

Is there a document somewhere describing best practice with regard to
error handling in vbscript? With regard to defensive programming
practices that should be observed.

Finally, in self protection against writing to files/folders that
don't exist, it looks like I'll be wrapping the write statements in
fso.FolderExists(sPathspec) tests. Is that about right?

Thanks in advance for any comments you might want to volunteer.

-- Roy Zider
FUBARinSFO
2008-02-02 02:00:20 UTC
Permalink
Correction: am seeing error messages from wscript, and haven't tested
errorlevel from cscript.
Anthony Jones
2008-02-02 15:00:01 UTC
Permalink
Post by FUBARinSFO
While confused that I wasn't getting runtiime error messages when I
tried to write to files with invalid paths, I poked around see that
error handling is generally absent in vbscript. Since I make so few
errors in my programs, this has never been an issue for me....not.
Is there a document somewhere describing best practice with regard to
error handling in vbscript? With regard to defensive programming
practices that should be observed.
Finally, in self protection against writing to files/folders that
don't exist, it looks like I'll be wrapping the write statements in
fso.FolderExists(sPathspec) tests. Is that about right?
Thanks in advance for any comments you might want to volunteer.
Yes its generally good practice to avoid using errors to run exceptional
code when the exception is detectable (that is true in any language). So
the choice to use FolderExists in this case is a good one (regardless of any
lack of error handling).

As to general defensive programming, IMO if that is important to you stop
using VBScript.

If your doing system admin sort of things consider Powershell, if your doing
ASP the consider JScript or ASP.NET.
--
Anthony Jones - MVP ASP/ASP.NET
Owen Gilmore
2008-02-04 23:06:18 UTC
Permalink
Post by Anthony Jones
Post by FUBARinSFO
While confused that I wasn't getting runtiime error messages when I
tried to write to files with invalid paths, I poked around see that
error handling is generally absent in vbscript.  Since I make so few
errors in my programs, this has never been an issue for me....not.
Is there a document somewhere describing best practice with regard to
error handling in vbscript?  With regard to defensive programming
practices that should be observed.
Finally, in self protection against writing to files/folders that
don't exist, it looks like I'll be wrapping the write statements in
fso.FolderExists(sPathspec) tests.  Is that about right?
Thanks in advance for any comments you might want to volunteer.
Yes its generally good practice to avoid using errors to run exceptional
code when the exception is detectable (that is true in any language).  So
the choice to use FolderExists in this case is a good one (regardless of any
lack of error handling).
As to general defensive programming, IMO if that is important to you stop
using VBScript.
If your doing system admin sort of things consider Powershell, if your doing
ASP the consider JScript or ASP.NET.
--
Anthony Jones - MVP ASP/ASP.NET- Hide quoted text -
- Show quoted text -
Doesn't Jscript do the same things as vbscript but more verbosely and
with all the Java annoyances and quirks? That's why I never bothered
with it (plus, VB script just seemed easier to learn and in more
demand).

Agree about Powershell, though. Anybody now learning administrative
scripting would do better to concentrate on Powershell instead of
VBscript.

-OG
Anthony Jones
2008-02-05 09:04:22 UTC
Permalink
Post by Owen Gilmore
Doesn't Jscript do the same things as vbscript but more verbosely and
with all the Java annoyances and quirks? That's why I never bothered
with it (plus, VB script just seemed easier to learn and in more
demand).
Yes VB script is easier to learn which is handy since that was the objective
of language from the outset and why it has the word 'Basic' in its name. So
for those whose primary focus is systems administration and have neither the
time nor the inclination to become software developers then VBScript is a
good compromise. The lack of strong (or even middling) error handling is
often inconsequential in this area, either the script fails catastrophically
or it succeeds.

Also you are correct that VBScript is more in demand in the world of
administrative scripts. You only have run through a few messages in this NG
to see that it may as well have been called it m.p.admin.scripting.
JScript is far less popular to script admin tasks.

I'm not sure I understand your comments about JScript being more verbose, if
anything VBScript is more verbose ( compare } with End If), however, such
verbosity is not a necessarily a bad thing. One thing that it seems
VBScripters find challenging (both in the admin world and the ASP world ) is
abstraction to functions. JScript quickly becomes unreadable without the
use of functions whereas quite long VBScripts can remain followable (if not
ideal) without using functions.
Post by Owen Gilmore
Agree about Powershell, though. Anybody now learning administrative
scripting would do better to concentrate on Powershell instead of
VBscript.
Yet Powershell syntax is even more opaque than JScript. Until there is much
better documentation and better tools (notepad just doesn't cut it here)
Powershell is only useful if you need its benefits (such as better error
trapping). Bear in mind the many of the .NET classes that you can use in
Powershell have COM interop interfaces and can be leveraged in VBScript. In
fact thinking about it Visual Studio Express is an excellent code editor so
VB.Net could be an option it is better documented and a lot easier to follow
than Powershell's unix-isms.

In the long run I expect Powershell to become the norm for administrative
scripting.
--
Anthony Jones - MVP ASP/ASP.NET
Paul Randall
2008-02-02 17:38:51 UTC
Permalink
Post by FUBARinSFO
While confused that I wasn't getting runtiime error messages when I
tried to write to files with invalid paths, I poked around see that
error handling is generally absent in vbscript. Since I make so few
errors in my programs, this has never been an issue for me....not.
Is there a document somewhere describing best practice with regard to
error handling in vbscript? With regard to defensive programming
practices that should be observed.
Finally, in self protection against writing to files/folders that
don't exist, it looks like I'll be wrapping the write statements in
fso.FolderExists(sPathspec) tests. Is that about right?
Thanks in advance for any comments you might want to volunteer.
Hi, Roy
I don't know of any best-practice document.
In a very few cases, you can design your script so that ignoring
errors (by using 'On Error Resume Next' at the beginning of the
script, and never checking the Err object) produces the desired
result. The WMI-related VBScripts produced by the Scripting Guy's
ScriptOMatic.HTA are one example where that technique works very well.

In most cases, at various points in your script you can choose to
either 1) let the system handle the errors by reporting them in a
message box and aborting the script (by using 'On Error GoTo 0), 2)
handle the errors yourself, (by using 'On Error Resume Next' and
checking the Err object after every statement and doing something
intelligent for each Err.Number encountered, or 3) carefully design
your script so that a combination of 1) and 2) give you the desired
result.

In general, I think of the 'On Error GoTo 0' statement as switching to
system error handling mode, and 'On Error Resume Next' as switching to
scripter error handling mode. In scripter error handling mode, the
script can either ignore errors or check for them and handle them in
some way. If the script ignores errors, then the system will change
the sequence of statements that are executed. This is the scripter's
challenge: to understand how the execution sequence may be changed,
and ensure that this doesn't cause undesired side effects.

The scripting help file, SCRIPT56.CHM, has a few paragraphs that I
think accurately describe the error handling features, but is not good
at explaining the implications of those features. The help file has
an entry in the index for 'On Error Statement'. I would suggest that
you very carefully read the Remarks section and build some test
scripts that include subroutines and that demonstrate everything that
the remarks talk about.

The scripting help files talks a little about how the sequence of
statements executed may be changed: "On Error Resume Next causes
execution to continue with the statement immediately following the
statement that caused the run-time error, or with the statement
immediately following the most recent call out of the procedure
containing the On Error Resume Next statement." It does not talk
about what happens when scripter error handling mode is on and the
script encounters an error in flow-control statements, like
If...Then...Else or Select Case constructs. Your test scripts should
demonstrate how an error in any part of these constructs changes the
execution sequence of statements.

Occasionally you may find or be given scripts or snippets or routines
which have worked very well on someone's system, but which work badly
on your system. One common problem is that many people don't always
start their scripts with an 'Option Explicit' statement. And maybe
you do use it in your scripts. An unDimmed variable in the snippet
may have been no problem in the original code, but may now change
program flow in your system, and cause unintended consequences,
depending on the error handling mode in effect when the unDimmed
variable is encountered. Your test scripts should demonstrate this
too, by showing different results for the same script when 'Option
Explicit' is in effect or commented out.

I hope this help a little.

-Paul Randall
ekkehard.horner
2008-02-02 19:33:15 UTC
Permalink
Post by FUBARinSFO
While confused that I wasn't getting runtiime error messages when I
tried to write to files with invalid paths, I poked around see that
error handling is generally absent in vbscript. Since I make so few
errors in my programs, this has never been an issue for me....not.
Is there a document somewhere describing best practice with regard to
error handling in vbscript? With regard to defensive programming
practices that should be observed.
Finally, in self protection against writing to files/folders that
don't exist, it looks like I'll be wrapping the write statements in
fso.FolderExists(sPathspec) tests. Is that about right?
[...]
The VBScript way of errorhandling is to abort the script. You can disable this
feature by using "On Error Resume Next" globally (at the top of your code).
That is like driving with closed eyes to avoid being dazzled by the headlights
of other cars.

You should make sure that your script runs correctly given normal conditions.
E.g.: If a program reads a config file in its own directory, it's ok just
to open it

Dim oTS : Set oTS = oFS.OpenTextFile( ".\config.txt" )

a user who deletes that config file deserves what he gets. If the program
reads a local data file that may not be there, test before you jump

Dim sFSpec : sFSpec = "c:\exchange\data\20080201\maynotbethere.txt"
If oFS.FileExists( sFSpec ) Then
Dim oTS : Set oTS = oFS.OpenTextFile( sFSpec )
...
Else
MsgBox sFSpec & " not found! ..."
...
End If

If the user succeeds in deleting the file after your test but before
your script has processed it - let him blame himself.

If you have to make arrangements against bad luck - your script writes
to a file on a remote server - use OERN in a strictly local way:

Dim oFS : Set oFS = CreateObject( "Scripting.FileSystemObject" )
Dim sFSpec : sFSpec = "\\fangorn\tmp\test\something.txt"
Dim bOk : bOk = False
Dim oTS, nCnt
If oFS.FolderExists( oFS.GetParentFolderName( sFSpec ) ) Then
Do
On Error Resume Next
Set oTS = oFS.CreateTextFile( sFSpec, True )
If 0 <> Err.Number Then Exit Do
On Error GoTo 0
For nCnt = 1 To 10
' 20 lines of building output ....
On Error Resume Next
oTS.WriteLine nCnt
If 0 <> Err.Number Then Exit Do
On Error GoTo 0
' 40 lines of something else ....
Next
On Error Resume Next
oTS.Close
If 0 <> Err.Number Then Exit Do
On Error GoTo 0
bOk = True
MsgBox "Looks good!"
Loop Until True
If Not bOk Then
MsgBox Err.Number & ": " & Err.Description
End If
Else
MsgBox oFS.GetParentFolderName( sFSpec ) & " not found! ..."
End If

(BTW: If you keep your OERN/OEG0 close together (just one line of code
that could fail) you can skip all the philological research and testing
Paul proposed.)

If you now think that this is a bit too much of hassle, I agree. So for
tasks that need more than a few checks by normal code and perhaps one
or two local OERNs, you should follow Anthony's advice: switch to another
language.
FUBARinSFO
2008-02-03 02:37:57 UTC
Permalink
Folks:

These are quite thoughtful submissions. My comments here will not do
them justice, I'm afraid.

1. Powershell (Monad) (from Anthony Jones)

I've seen references to it, but thought it was a third-party app.
Googling "what is powershell" I came eventually to this interview.
Unfortunately the interviewer is clueless, but Snover is an
evangelist.

Jeffrey Snover - Monad explained
Posted by The Channel 9 Team // Sun, Jun 24, 2007 4:49 PM
http://channel9.msdn.com/ShowPost.aspx?PostID=26795#26795.

Since I personally still use the command line for a lot of work, I am
very receptive to this pitch. Years ago the lack of a "unique" filter
(output unique lines from a text file) led me to write my own in
assembly language to take the piped output from sort. The toolbox
mode is still a great way to get work done. I still drop to command
window to use "dir" to filter and organize file names and folders.

It appears that here the effort is to integrate the CLI with the GUI
and provide a sort of grand synthesis of all current technologies.
The problem is that it requires what is a major effort to master yet
another environment - think Java. "There's lots of great systems out
there". True - and here is another. The mention of "curly
brackets" (otherwise known as braces) being embraced by the team
turned me off, I'm afraid - I'm not a fan of context-free grammar (a
boon to compiler writers) and find the braces more annoying than
helpful. Nowhere is "open systems" mentioned in the interview, so
presumably this is a proprietary Microsoft environment, extending C#
and .NET technologies. And neither is "error handling" - my main
concern at this point.

So as predisposed as I am to this message, I'll have to put aside
enough time (a week or two, at least) to get up to speed and write
some useful stuff before I'm ready to even begin to use this
environment. But thank you for the pointer, which I wouldn't have
otherwise pursued but for your thoughtful post.

2. Defensive programming

Anthony Jones also recommends not using VBS if you're concerned about
error handling. I was afraid of that. I always use Option Explicit,
and do try to wrap possible exceptions in some sort of error-handling
code. But even using try-catch is a stretch for some of us, so if I
am in any way representative of the casual programmer it is a constant
struggle to set up your code to handle exceptions On Error ... is
something I used to use, but found it bothersome. That is my
mistake. I used to program from templates that I called up with pre-
formed structure, but have fallen off the wagon on this. All of these
comments make me think that if I'm serious about this I should
reactivate my templates and have another go at that method.

3. On Error Resume Next/ GoTo 0

Paul Randall has suggested reading the remarks in the script56.chm
file concerning the On Error statement. It brings back my long-ago
impression about how much of an afterthought error handling has been
for the BASIC developers. A single snippet of code, with no context,
serves as the only example of On Error Resume Next. No example of On
Error GoTo 0, let alone On Error GoTo <label of error handler>. Due
caution is mentioned that results are unpredictable depending on the
host environment if you don't have On Error statements in your code.

I found a better starting reference for this construct in the on the
MSDN site:
Unstructured Exception Handling Overview
http://msdn2.microsoft.com/en-us/library/sf1hwa21(VS.80).aspx

Here at least there are examples, and honesty in advertising by
calling it "unstructured". It also has this note:

Note
Unstructured error handling using On Error can degrade application
performance and result in code that is difficult to debug and
maintain. Structured error handling is the recommended method. For
more information, see Structured Exception Handling Overview for
Visual Basic.
http://msdn2.microsoft.com/en-us/library/8a9f2ew0(VS.80).aspx

- which takes us back to the Try - Catch - Finally construct.

What I find particularly interesting is that none of these sources
make note of the possibility that if you have a runaway script, say,
you won't be able to break out of it with Ctrl-Break or Ctrl-C. If
you've run the script from an open command window, using cscript, Ctrl-
Break/Ctrl-C will work to break script execution. But if you've
started the script from the Windows shell, double clicking on the .vbs
file from Windows Explorer, you can't abort script execution except by
killing the task inside Task Manager. This is the problem that got me
started on this path in the first place, and I am somewhat surprised
to have found it hardly mentioned. There used to be a Ctrl-Break
handler in BASIC (wasn't there?), but was used to turn it off.
Evidently it's turned off in VBS now permanently, or else Windows
Explorer doesn't pass it any keystrokes.

Ekkehard Horner pretty much captures my take on the spirit of On Error
Resume Next when he remarks that "That is like driving with closed
eyes to avoid being dazzled by the headlights of other cars."

Reading these resources, it's clear I'm going to have to incorporate
On Error into my programs if I want to have more than a trivial error
handling regime.

4. Example code styles

I gave an example of a little wrapper I've started using in my code,
to protect against file I/O errors. Ekkehard gives many more examples
of coding style, one of which I had never seen before: a coherent
reason for using a multi-statement line. It used to be that you did
this in BASIC to save program memory. I always thought it made the
code uneditable. But he has Dimed the variable as he uses it, in the
below lines from his posting:

Dim sFSpec : sFSpec = "c:\exchange\data\20080201\maynotbethere.txt"
Dim oTS : Set oTS = oFS.OpenTextFile( sFSpec )
Dim bOk : bOk = False

I'll have to experiment with that, as my style is to place all vars up
front, no matter where they're used, which makes for some awkward
jumping around. But he has the same economy of naming that I prefer:
'o' rather than 'obj' for object, 'b' rather than 'bln' for boolean,
's' rather than 'str' for string, and so forth - against VBS
recommended naming practice, but far preferable imho.

The 'Do...Loop Until True' construct I also hadn't seen before. I use
While True ... Wend for blocks of code I want to preserve as a way of
"commenting them out" at runtime. I assumed he was doing that here as
well - except that if this defines a "block", then I assume it is the
"block of code" referred to in the remarks on "OERN" and so makes it
local. The 'Exit Do' confirms this usage, so it's another construct I
can use to help structure this error handling. It's a different way
of structuring the error handler, which in the examples I've seen (and
programmed myself) is placed sfter an Exit Sub statement, with error
handling code at the end. This is another compaction of code style,
where the error handling is embedded in with the code logic -
something I try mightily to avoid, generally by putting the handlers
at the end of the functions, and not using subs at all but rather
functions with return codes.

Overall, I really want to thank the three of you for your thoughtful
comments. This is great stuff. I'm going to mush along a bit longer
in VBS and incorporate your suggestions, but will be spending more
time in the future looking for a way to get the same work done (in
another language) that has error handling as a more intrinsic feature
of the language.

-- Roy Zider
ekkehard.horner
2008-02-03 10:51:02 UTC
Permalink
Post by FUBARinSFO
These are quite thoughtful submissions. My comments here will not do
them justice, I'm afraid.
Far from it!
Post by FUBARinSFO
1. Powershell (Monad) (from Anthony Jones)
[...]
Post by FUBARinSFO
2. Defensive programming
Anthony Jones also recommends not using VBS if you're concerned about
error handling. I was afraid of that. I always use Option Explicit,
and do try to wrap possible exceptions in some sort of error-handling
code. But even using try-catch is a stretch for some of us, so if I
am in any way representative of the casual programmer it is a constant
struggle to set up your code to handle exceptions On Error ... is
something I used to use, but found it bothersome. That is my
mistake. I used to program from templates that I called up with pre-
formed structure, but have fallen off the wagon on this. All of these
comments make me think that if I'm serious about this I should
reactivate my templates and have another go at that method.
In my opinion, in VBScript you should concentrate on defensive programming,
that is checking the conditions you rely on carefully with normal/standard
code. OERN should be reserved for a few special cases where gaps of design/
implementation

Function RegKeyExists( oShell, sKey )
Dim sVal
On Error Resume Next
sVal = oShell.RegRead( sKey )
RegKeyExists = (0 = Err.Number)
On Error Goto 0
End Function

quirks of the OS

Sub recurseDir( oFolder, ... )
WScript.Echo oFolder.Path ' e.g. System Volume Information
Dim nCnt
On Error Resume Next
nCnt = oFolder.SubFolders|Files.Count
If 0 <> Err.Number Then
What shall we do with this Hidden/System folder?
...

or volatile resources (Network, Servers) compel extra efforts.
Post by FUBARinSFO
3. On Error Resume Next/ GoTo 0
Paul Randall has suggested reading the remarks in the script56.chm
file concerning the On Error statement. It brings back my long-ago
impression about how much of an afterthought error handling has been
for the BASIC developers. A single snippet of code, with no context,
serves as the only example of On Error Resume Next. No example of On
Error GoTo 0, let alone On Error GoTo <label of error handler>. Due
There is no "On Error Goto <Label>" in VBScript.
Post by FUBARinSFO
caution is mentioned that results are unpredictable depending on the
host environment if you don't have On Error statements in your code.
I found a better starting reference for this construct in the on the
Unstructured Exception Handling Overview
http://msdn2.microsoft.com/en-us/library/sf1hwa21(VS.80).aspx
This deals with VB, not VBScript. So don't get overconfident/optimistic.

[...]
Post by FUBARinSFO
What I find particularly interesting is that none of these sources
make note of the possibility that if you have a runaway script, say,
you won't be able to break out of it with Ctrl-Break or Ctrl-C. If
you've run the script from an open command window, using cscript, Ctrl-
Break/Ctrl-C will work to break script execution. But if you've
started the script from the Windows shell, double clicking on the .vbs
file from Windows Explorer, you can't abort script execution except by
killing the task inside Task Manager. This is the problem that got me
That's one reason for avoiding wscript.exe.
There is a timeout feature (//T:<n>), but that can't be seen as a substitute
for decent signal handling.

[...]
Post by FUBARinSFO
4. Example code styles
I gave an example of a little wrapper I've started using in my code,
to protect against file I/O errors. Ekkehard gives many more examples
of coding style, one of which I had never seen before: a coherent
reason for using a multi-statement line. It used to be that you did
this in BASIC to save program memory. I always thought it made the
code uneditable. But he has Dimed the variable as he uses it, in the
Dim sFSpec : sFSpec = "c:\exchange\data\20080201\maynotbethere.txt"
Dim oTS : Set oTS = oFS.OpenTextFile( sFSpec )
Dim bOk : bOk = False
I think that variables should be

declared (Dim) immediately before the first use (not in a block at the
beginning of the script/function)

initialized immediately

This isn't always feasible (nested loops, variables used for different
purposes) and makes it to easy to skip proper documentation (comments).
Perhaps

Dim sFSpec ''< list of computers to check; created by otherscript.vbs
sFSpec = "c:\exchange\data\20080201\maynotbethere.txt"

would be better
Post by FUBARinSFO
I'll have to experiment with that, as my style is to place all vars up
front, no matter where they're used, which makes for some awkward
jumping around.
That's why I don't like long Dim lists of variables at the start of the
script - some of them not even used anymore.
Post by FUBARinSFO
'o' rather than 'obj' for object, 'b' rather than 'bln' for boolean,
's' rather than 'str' for string, and so forth - against VBS
recommended naming practice, but far preferable imho.
I see the hungarian prefix as a kind of "programmer, pay attention"
flag useful in not strictly typed languages. It helps me not to forget
the Set in object assignments or the type cast in boolean expressions.
But I wouldn't normally differentiate between int, long, single, or
double; just nNumber is enough for me. For member variables I use
"m_"

Public Property Let Name( sName )
...
m_sName = sName
End Property

but that may be caused by an overdosis of VC 6.0 programming.
Post by FUBARinSFO
The 'Do...Loop Until True' construct I also hadn't seen before. I use
While True ... Wend for blocks of code I want to preserve as a way of
"commenting them out" at runtime. I assumed he was doing that here as
well - except that if this defines a "block", then I assume it is the
"block of code" referred to in the remarks on "OERN" and so makes it
local. The 'Exit Do' confirms this usage, so it's another construct I
By "local" I just mean: not global at the start of the script, but as
a brace/bracket around the single statement that could fail.

The "Do..Loop Until True" is an attempt to add some kind of "On Error
Goto <Label>" to VBScript. All "Exit Do" will 'jump' to the statement
after the "Do" where the actual error handling can be centralized.
It's a hack, because you can't use nested "Do .. Loop"; if you perceive
that you spend more time on thinking about creative juggling of loop
constructs than on the problems your program should solve, it's time to
switch languages.
Post by FUBARinSFO
can use to help structure this error handling. It's a different way
of structuring the error handler, which in the examples I've seen (and
programmed myself) is placed sfter an Exit Sub statement, with error
handling code at the end. This is another compaction of code style,
where the error handling is embedded in with the code logic -
something I try mightily to avoid, generally by putting the handlers
at the end of the functions, and not using subs at all but rather
You can't do that in VBScript (without a hack; exiting out of a Sub
or Function could be an alternative to the "Exit <LoopType>" approach).
Post by FUBARinSFO
functions with return codes.
Overall, I really want to thank the three of you for your thoughtful
comments. This is great stuff. I'm going to mush along a bit longer
in VBS and incorporate your suggestions, but will be spending more
time in the future looking for a way to get the same work done (in
another language) that has error handling as a more intrinsic feature
of the language.
You are welcome; I thank you for posing such an interesting problem.
Anthony Jones
2008-02-03 17:11:29 UTC
Permalink
Post by ekkehard.horner
Post by FUBARinSFO
These are quite thoughtful submissions. My comments here will not do
them justice, I'm afraid.
Far from it!
Post by FUBARinSFO
1. Powershell (Monad) (from Anthony Jones)
[...]
Post by FUBARinSFO
2. Defensive programming
Anthony Jones also recommends not using VBS if you're concerned about
error handling. I was afraid of that. I always use Option Explicit,
and do try to wrap possible exceptions in some sort of error-handling
code. But even using try-catch is a stretch for some of us, so if I
am in any way representative of the casual programmer it is a constant
struggle to set up your code to handle exceptions On Error ... is
something I used to use, but found it bothersome. That is my
mistake. I used to program from templates that I called up with pre-
formed structure, but have fallen off the wagon on this. All of these
comments make me think that if I'm serious about this I should
reactivate my templates and have another go at that method.
In my opinion, in VBScript you should concentrate on defensive
programming,
Post by ekkehard.horner
that is checking the conditions you rely on carefully with normal/standard
code. OERN should be reserved for a few special cases where gaps of design/
implementation
Function RegKeyExists( oShell, sKey )
Dim sVal
On Error Resume Next
sVal = oShell.RegRead( sKey )
RegKeyExists = (0 = Err.Number)
On Error Goto 0
End Function
I've seen this On Error Goto 0 at the end of function quite a lot. Is it
really necessary?
--
Anthony Jones - MVP ASP/ASP.NET
ekkehard.horner
2008-02-03 17:37:27 UTC
Permalink
[...]
Post by Anthony Jones
Post by ekkehard.horner
Function RegKeyExists( oShell, sKey )
Dim sVal
On Error Resume Next
sVal = oShell.RegRead( sKey )
RegKeyExists = (0 = Err.Number)
On Error Goto 0
End Function
I've seen this On Error Goto 0 at the end of function quite a lot. Is it
really necessary?
According to the VBScript Docs:

When a procedure is exited, the error-handling capability reverts to
whatever error-handling was in place before entering the exited procedure.

it is not. But I write
Post by Anthony Jones
Post by ekkehard.horner
On Error Resume Next
On Error Goto 0
before I insert any lines between the 'braces' and that way I'm guarded
against blunders when code is added in the future.
Al Dunbar
2008-02-03 19:57:31 UTC
Permalink
Post by Anthony Jones
Post by ekkehard.horner
Post by FUBARinSFO
These are quite thoughtful submissions. My comments here will not do
them justice, I'm afraid.
Far from it!
Post by FUBARinSFO
1. Powershell (Monad) (from Anthony Jones)
[...]
Post by FUBARinSFO
2. Defensive programming
Anthony Jones also recommends not using VBS if you're concerned about
error handling. I was afraid of that. I always use Option Explicit,
and do try to wrap possible exceptions in some sort of error-handling
code. But even using try-catch is a stretch for some of us, so if I
am in any way representative of the casual programmer it is a constant
struggle to set up your code to handle exceptions On Error ... is
something I used to use, but found it bothersome. That is my
mistake. I used to program from templates that I called up with pre-
formed structure, but have fallen off the wagon on this. All of these
comments make me think that if I'm serious about this I should
reactivate my templates and have another go at that method.
In my opinion, in VBScript you should concentrate on defensive
programming,
Post by ekkehard.horner
that is checking the conditions you rely on carefully with
normal/standard
code. OERN should be reserved for a few special cases where gaps of
design/
Post by ekkehard.horner
implementation
Function RegKeyExists( oShell, sKey )
Dim sVal
On Error Resume Next
sVal = oShell.RegRead( sKey )
RegKeyExists = (0 = Err.Number)
On Error Goto 0
End Function
I've seen this On Error Goto 0 at the end of function quite a lot. Is it
really necessary?
IMHO, not really necessary, and does absolutely nothing, as the error
environment will revert to that of the caller once the function exits.

But (and I think someone suggested this earlier) it could be "defensive", as
it brackets the code that needs this setting. Supposing one needed to add
some post-processing code that should have on error set to "goto 0". If it
is already there, it will be less likely to be missed out.

As an example, I end ALL of my internal batch routines (i.e.
"CALL:GET_input") with "GOTO:EOF", even the very last one in the file. If I
didn't, and added yet one more routine on the end, the previously last one
would likely run onto the new one with potentially disastrous effect.

/Al
Anthony Jones
2008-02-03 11:59:18 UTC
Permalink
Post by FUBARinSFO
These are quite thoughtful submissions. My comments here will not do
them justice, I'm afraid.
1. Powershell (Monad) (from Anthony Jones)
I've seen references to it, but thought it was a third-party app.
Googling "what is powershell" I came eventually to this interview.
Unfortunately the interviewer is clueless, but Snover is an
evangelist.
Jeffrey Snover - Monad explained
Posted by The Channel 9 Team // Sun, Jun 24, 2007 4:49 PM
http://channel9.msdn.com/ShowPost.aspx?PostID=26795#26795.
Since I personally still use the command line for a lot of work, I am
very receptive to this pitch. Years ago the lack of a "unique" filter
(output unique lines from a text file) led me to write my own in
assembly language to take the piped output from sort. The toolbox
mode is still a great way to get work done. I still drop to command
window to use "dir" to filter and organize file names and folders.
It appears that here the effort is to integrate the CLI with the GUI
and provide a sort of grand synthesis of all current technologies.
The problem is that it requires what is a major effort to master yet
another environment - think Java. "There's lots of great systems out
there". True - and here is another. The mention of "curly
brackets" (otherwise known as braces) being embraced by the team
turned me off, I'm afraid - I'm not a fan of context-free grammar (a
boon to compiler writers) and find the braces more annoying than
helpful. Nowhere is "open systems" mentioned in the interview, so
presumably this is a proprietary Microsoft environment, extending C#
and .NET technologies. And neither is "error handling" - my main
concern at this point.
So as predisposed as I am to this message, I'll have to put aside
enough time (a week or two, at least) to get up to speed and write
some useful stuff before I'm ready to even begin to use this
environment. But thank you for the pointer, which I wouldn't have
otherwise pursued but for your thoughtful post.
Powershell is the script language for the .NET age of MS. I'm surprised
your searching has turned up such little results see:-

http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx

I feel the same about {} as you, it was a useful shortcut to a compilier
back in the days when nightly builds were necessary cos it took all night to
do the build. However, { } is well embedded in programmer psyche now and
you do become used to it fairly rapidly.

I'm not sure I understand your comment re 'open systems' if that is a
consideration what are you doing using VBScript? Powershell is primarily
aimed and windows administrative tasks so being 'open' would hardly be an
advantage. As I mentioned if your intent is not administrative tasks then
you should be looking to JScript for structured error handling.

Another alternative would be Python.
Post by FUBARinSFO
2. Defensive programming
Anthony Jones also recommends not using VBS if you're concerned about
error handling. I was afraid of that. I always use Option Explicit,
and do try to wrap possible exceptions in some sort of error-handling
code. But even using try-catch is a stretch for some of us, so if I
am in any way representative of the casual programmer it is a constant
struggle to set up your code to handle exceptions On Error ... is
something I used to use, but found it bothersome. That is my
mistake. I used to program from templates that I called up with pre-
formed structure, but have fallen off the wagon on this. All of these
comments make me think that if I'm serious about this I should
reactivate my templates and have another go at that method.
It isn't really reasonable to expect a 'casual programmer' to program
defensively. VBScript and its kin have encouraged a great deal of 'casual'
programming which is the reason why it has been so successful and the reason
many 'casual' programmers achieve their aims successfully.

However the comes a point where a requirement has sufficient complexity
where the 'casual' approach just isn't sufficient. Then one of two things
happen:

1) the casual programmer becomes aware of the current approaches limitations
and sees the need climb a learning curve for what seems only a little
payback (after all what has gone on before has been successful).

2) the casual programmer remains unaware that the current approaches have
limitations and struggles to achieve the requirement. Something is
delivered but its fragile and needs hand holding and frequent maintenance to
continue working. Eventually it suffers from 'modification fatigue' and
breaks down completely.

It sounds like a template approach can help but I'm not sure I understand
what you mean by 'template'. I've seen the 'casual' programmer cut'n'paste
existing code and tweak it to do what they want it to without understanding
how the program as whole wortks, is this what you mean?
Post by FUBARinSFO
3. On Error Resume Next/ GoTo 0
Paul Randall has suggested reading the remarks in the script56.chm
file concerning the On Error statement. It brings back my long-ago
impression about how much of an afterthought error handling has been
for the BASIC developers. A single snippet of code, with no context,
serves as the only example of On Error Resume Next. No example of On
Error GoTo 0, let alone On Error GoTo <label of error handler>. Due
caution is mentioned that results are unpredictable depending on the
host environment if you don't have On Error statements in your code.
I found a better starting reference for this construct in the on the
Unstructured Exception Handling Overview
http://msdn2.microsoft.com/en-us/library/sf1hwa21(VS.80).aspx
Here at least there are examples, and honesty in advertising by
Note
Unstructured error handling using On Error can degrade application
performance and result in code that is difficult to debug and
maintain. Structured error handling is the recommended method. For
more information, see Structured Exception Handling Overview for
Visual Basic.
http://msdn2.microsoft.com/en-us/library/8a9f2ew0(VS.80).aspx
- which takes us back to the Try - Catch - Finally construct.
What I find particularly interesting is that none of these sources
make note of the possibility that if you have a runaway script, say,
you won't be able to break out of it with Ctrl-Break or Ctrl-C. If
you've run the script from an open command window, using cscript, Ctrl-
Break/Ctrl-C will work to break script execution. But if you've
started the script from the Windows shell, double clicking on the .vbs
file from Windows Explorer, you can't abort script execution except by
killing the task inside Task Manager. This is the problem that got me
started on this path in the first place, and I am somewhat surprised
to have found it hardly mentioned. There used to be a Ctrl-Break
handler in BASIC (wasn't there?), but was used to turn it off.
Evidently it's turned off in VBS now permanently, or else Windows
Explorer doesn't pass it any keystrokes.
In windows not all applications are attached to some kind of console from
which a Ctrl-Break etc can be recieved. You can kill process in task
manager. Structured error handling won't help eliminate infinite loops in
code though.
Post by FUBARinSFO
Ekkehard Horner pretty much captures my take on the spirit of On Error
Resume Next when he remarks that "That is like driving with closed
eyes to avoid being dazzled by the headlights of other cars."
Reading these resources, it's clear I'm going to have to incorporate
On Error into my programs if I want to have more than a trivial error
handling regime.
To be frank the only non-trivial way to do error handling in VBScript is to
use Resume Next and test Err.Number after every statement (or at least every
statement that has reasonable chance of failing). Real ugly.
Post by FUBARinSFO
4. Example code styles
I gave an example of a little wrapper I've started using in my code,
to protect against file I/O errors. Ekkehard gives many more examples
of coding style, one of which I had never seen before: a coherent
reason for using a multi-statement line. It used to be that you did
this in BASIC to save program memory. I always thought it made the
code uneditable. But he has Dimed the variable as he uses it, in the
Dim sFSpec : sFSpec = "c:\exchange\data\20080201\maynotbethere.txt"
Dim oTS : Set oTS = oFS.OpenTextFile( sFSpec )
Dim bOk : bOk = False
I'll have to experiment with that, as my style is to place all vars up
front, no matter where they're used, which makes for some awkward
'o' rather than 'obj' for object, 'b' rather than 'bln' for boolean,
's' rather than 'str' for string, and so forth - against VBS
recommended naming practice, but far preferable imho.
I also use what I like to refer to as 'slob' prefixing. String, Long,
Object and Boolean. They cover probably about 90% of all variables created.
I stick with byt, sng, dbl for the rare times I use them.

I also use g for global scope, m for module scope (only in classes in
VBScript), r for ByRef parameters, v for ByVal parameters and c for
constants (I hate those shouty all upper constant names).

However some really common objects like FileSystemObject get fso or gfso (if
instanced globally).

E.g.

Const gclMaxThingyCount = 50
Dim gfso : Set gfso = CreateObject("Scripting.FileSystemObject")

Function DoStuff(ByVal vsDontModMe, rsImBigDontCopyMe)

End Function

Pre-emptive: Using type prefixes is a good practive to help identifiy what
type a variable is supposed to hold, its worth bearing in mind that since
most variables are variants they can actually hold any type. I've seen
plenty of code using a variable such as lUserID that works fine despite the
variable being drawn from an ASP QueryString and actually be a String not a
Long. Of course that means occasionaly strange things happen so it worth
scrutanising variable assignents to ensure the correct types are being
assigned, e.g. using CLng etc.
Post by FUBARinSFO
The 'Do...Loop Until True' construct I also hadn't seen before. I use
While True ... Wend for blocks of code I want to preserve as a way of
"commenting them out" at runtime. I assumed he was doing that here as
well - except that if this defines a "block", then I assume it is the
"block of code" referred to in the remarks on "OERN" and so makes it
local. The 'Exit Do' confirms this usage, so it's another construct I
can use to help structure this error handling. It's a different way
of structuring the error handler, which in the examples I've seen (and
programmed myself) is placed sfter an Exit Sub statement, with error
handling code at the end. This is another compaction of code style,
where the error handling is embedded in with the code logic -
something I try mightily to avoid, generally by putting the handlers
at the end of the functions, and not using subs at all but rather
functions with return codes.
That is another approach that can create reasonable structure, I've
certainly seen plenty of C code where that was the case. However you loose
the true function semantic such that functions can no longer participate in
expressions as they are designed to. E.g. this:-

Function fnA(x, y)
fnA = Do some stuff with x and y
End Function

Function fnB(x, y)
fnB = Do some other stuff with x and y
End Function

Function fnC(x, y, z)
fnC = fnA(fnB(x, y), z)
End Function


becomes:-


Function fnA(x, y, retVal)
On Error Resume Next
retVal = Do some stuff with x and y
fnA = 0 ' success
End Function

Function fnB(x, y, retVal)
On Error Resume Next
retVal = Do some other stuff with x and y
fnB = 0 ' success
End Function

Function fnC(x, y, z, retVal)
On Error Resume Next

Dim tmp
Dim lErrVal : errVal = fnA(x, y, tmp)

If lErrVal = 0 Then
fnC = fnB(tmp, z, retVal)
End If

End Function


The first approach is sooo much easier to follow but isn't very defensive.
The second approach is a little bit more defensive but what took 1 line of
code now takes 5. The more I think about it the more my head hurts,
VBScript just isn't up to the job if good error handling is required.
Post by FUBARinSFO
Overall, I really want to thank the three of you for your thoughtful
comments. This is great stuff. I'm going to mush along a bit longer
in VBS and incorporate your suggestions, but will be spending more
time in the future looking for a way to get the same work done (in
another language) that has error handling as a more intrinsic feature
of the language.
--
Anthony Jones - MVP ASP/ASP.NET
Al Dunbar
2008-02-03 19:51:13 UTC
Permalink
<snip>
Post by Anthony Jones
Post by FUBARinSFO
2. Defensive programming
Anthony Jones also recommends not using VBS if you're concerned about
error handling. I was afraid of that. I always use Option Explicit,
and do try to wrap possible exceptions in some sort of error-handling
code. But even using try-catch is a stretch for some of us, so if I
am in any way representative of the casual programmer it is a constant
struggle to set up your code to handle exceptions On Error ... is
something I used to use, but found it bothersome. That is my
mistake. I used to program from templates that I called up with pre-
formed structure, but have fallen off the wagon on this. All of these
comments make me think that if I'm serious about this I should
reactivate my templates and have another go at that method.
It isn't really reasonable to expect a 'casual programmer' to program
defensively. VBScript and its kin have encouraged a great deal of 'casual'
programming which is the reason why it has been so successful and the reason
many 'casual' programmers achieve their aims successfully.
However the comes a point where a requirement has sufficient complexity
where the 'casual' approach just isn't sufficient. Then one of two things
1) the casual programmer becomes aware of the current approaches limitations
and sees the need climb a learning curve for what seems only a little
payback (after all what has gone on before has been successful).
2) the casual programmer remains unaware that the current approaches have
limitations and struggles to achieve the requirement. Something is
delivered but its fragile and needs hand holding and frequent maintenance to
continue working. Eventually it suffers from 'modification fatigue' and
breaks down completely.
The above two scenarios do not refer simply to the transition from casual to
defensive, but from casual to, well, non-casual. That implies, among other
things, the application of a consistent structure to one's scripts, and the
anticipation of the sorts of "exceptional conditions" that could reasonably
arise. Taking a casual script that includes no error handling and fixing it
by sticking in extra error handling code is a patch-work approach at best.

Often the possibilities for exceptional conditions arise out of assumptions
made, consciously or otherwise. Before patching code based on such
assumptions, it is often useful to determine the assumptions made and
critically analyse them.

I think the word "error" in the term "error handling" often has the wrong
effect, as it makes us thing that things are wrong or incorrect. Certainly
if your code attempts to create a file in a non-existent folder, it will not
result in the successful creation of that file. If ignored, that might cause
other problems later on for the script.

But the lack of the folder in and of itself should not be considered an
error, just a condition, possibly an unexpected or undesired one. In some
contexts it could mean there is a definite misconfiguration of a computer,
which might be an error that might require some corrective action be taken
outside of the scope of your script. But if you take the possibility of a
folder's non-existence into account, you will find that it may not always be
an error in every case. One of my scripts routinely creates files in
non-existing folders - by creating them as required. The purpose of that
script is to generate a series of log files in a hierarchical folder
structure that is created as needed. In this context, the non-existence of a
folder is not an error, but an anticipated event.
Post by Anthony Jones
Post by FUBARinSFO
Ekkehard Horner pretty much captures my take on the spirit of On Error
Resume Next when he remarks that "That is like driving with closed
eyes to avoid being dazzled by the headlights of other cars."
Reading these resources, it's clear I'm going to have to incorporate
On Error into my programs if I want to have more than a trivial error
handling regime.
To be frank the only non-trivial way to do error handling in VBScript is to
use Resume Next and test Err.Number after every statement (or at least every
statement that has reasonable chance of failing). Real ugly.
Certainly not pretty, by a long shot. But better than anticipating and
testing for all of the possible conditions that could cause an operation to
fail. I think it better to let the error object tell you why the file
creation failed, rather than checking first that the folder exists (it could
still be deleted before your code gets to the point of failure), that you
have access to it (that could change), that the computer is online (it could
go offline), etc.etc.

Using resume next, err.clear (!), and err.number literally in code can
certainly obscure the logic of what the script is supposed to do when
conditions allow. Sometimes it is better to limit these to the lower level
routines, where they can be allowed to to their work uninterrupted and
forgotten about. Subs and Functions are for finer levels of detail, and what
is error checking if not a detail?
Post by Anthony Jones
Post by FUBARinSFO
4. Example code styles
I gave an example of a little wrapper I've started using in my code,
to protect against file I/O errors. Ekkehard gives many more examples
of coding style, one of which I had never seen before: a coherent
reason for using a multi-statement line. It used to be that you did
this in BASIC to save program memory. I always thought it made the
code uneditable. But he has Dimed the variable as he uses it, in the
Dim sFSpec : sFSpec = "c:\exchange\data\20080201\maynotbethere.txt"
Dim oTS : Set oTS = oFS.OpenTextFile( sFSpec )
Dim bOk : bOk = False
I'll have to experiment with that, as my style is to place all vars up
front, no matter where they're used, which makes for some awkward
'o' rather than 'obj' for object, 'b' rather than 'bln' for boolean,
's' rather than 'str' for string, and so forth - against VBS
recommended naming practice, but far preferable imho.
I also use what I like to refer to as 'slob' prefixing. String, Long,
Object and Boolean. They cover probably about 90% of all variables created.
I stick with byt, sng, dbl for the rare times I use them.
I also use g for global scope, m for module scope (only in classes in
VBScript), r for ByRef parameters, v for ByVal parameters and c for
constants (I hate those shouty all upper constant names).
However some really common objects like FileSystemObject get fso or gfso (if
instanced globally).
We all have our style preferences. I, for example, have a philosophical
dislike of RPN prefixing, although I do have a few of my own prefixes to
indicate certain things. Without starting a religious war over this, I think
I can safely say that, at least for the casual scripter, the style that is
best is the one that he finds the most useful.
Post by Anthony Jones
Post by FUBARinSFO
Overall, I really want to thank the three of you for your thoughtful
comments. This is great stuff. I'm going to mush along a bit longer
in VBS and incorporate your suggestions, but will be spending more
time in the future looking for a way to get the same work done (in
another language) that has error handling as a more intrinsic feature
of the language.
Agreed. this has been an interesting thread for such a short one, with some
good practical input from Anthony, Paul, and Ekkehard.

/Al
Paul Randall
2008-02-03 23:00:02 UTC
Permalink
Post by FUBARinSFO
Paul Randall has suggested reading the remarks in the script56.chm
file concerning the On Error statement.
Thanks for the feedback. I think it evoked inspired responses from
the heavyweights of this newsgroups.

Here is a short script that demonstrates a few effects of VBScript's
error handling. One problem I find while writing this kind of thing
is documenting it. Adding comments to the script, or echoing more
information can lead to a less understandable script. And a separate
text document to explain what is happening doesn't work well without
line numbered source code to refer to.

'Simple non-exhaustive test of 'On Error Resume Next'
' on subroutine calls.
Option Explicit
On Error Resume Next
Wscript.Echo "Started script"
ErrorSub1
Wscript.Echo "Wscript.Echo 1 - Back in Main from ErrorSub" &
Err.Number
Err.Clear
ErrorSub2
Wscript.Echo "Wscript.Echo 2 - Back in Main from ErrorSub" &
Err.Number
Err.Clear
ErrorSub3
Wscript.Echo "Wscript.Echo 3 - Back in Main from ErrorSub" &
Err.Number
Err.Clear
WScript.Echo "Reached end of script"
WScript.Quit

Sub ErrorSub1()
WScript.Echo "Entered ErrorSub1"
Err.Raise 1
Wscript.Echo "This statement never executed - Exitting Sub1"
End Sub

Sub ErrorSub2()
WScript.Echo "Entered ErrorSub2"
Err.Raise 2
Wscript.Echo "This statement never executed - Exitting Sub2"
End Sub

Sub ErrorSub3()
WScript.Echo "Entered ErrorSub3"
On Error Resume Next
EroorSub1 'Purposely misspelled subroutine name
Wscript.Echo "Wscript.Echo 4 - Back in ErrorSub3 from Sub" &
Err.Number
Err.Clear
ErrorSub1
Wscript.Echo "Wscript.Echo 5 - Back in ErrorSub3 from Sub" &
Err.Number
Err.Clear
On Error Goto 0
ErrorSub1
Wscript.Echo "This statement never executed - Exitting Sub3"
End Sub
Todd Vargo
2008-02-04 03:03:27 UTC
Permalink
Post by Paul Randall
Here is a short script that demonstrates a few effects of VBScript's
error handling. One problem I find while writing this kind of thing
is documenting it. Adding comments to the script, or echoing more
information can lead to a less understandable script. And a separate
text document to explain what is happening doesn't work well without
line numbered source code to refer to.
'Simple non-exhaustive test of 'On Error Resume Next'
' on subroutine calls.
Option Explicit
On Error Resume Next
Wscript.Echo "Started script"
ErrorSub1
Wscript.Echo "Wscript.Echo 1 - Back in Main from ErrorSub" &
Err.Number
Err.Clear
ErrorSub2
Wscript.Echo "Wscript.Echo 2 - Back in Main from ErrorSub" &
Err.Number
Err.Clear
ErrorSub3
Wscript.Echo "Wscript.Echo 3 - Back in Main from ErrorSub" &
Err.Number
Err.Clear
WScript.Echo "Reached end of script"
WScript.Quit
Sub ErrorSub1()
WScript.Echo "Entered ErrorSub1"
Err.Raise 1
Wscript.Echo "This statement never executed - Exitting Sub1"
End Sub
IMO, this code demonstrates how NOT to implement error handling. One should
not rely on a single instance of OERN to handle every possible error within
the script. As the code above demonstrates, OERN does not function as one
might expect when carried into a sub routine. An OERN should be placed in
each of the sub routines to handle errors on a localized basis.

Sub ErrorSub1()
WScript.Echo "Entered ErrorSub1"
On Error Resume Next
{statement that raises an error}
Select Case Err.Number
Case 1
'Expected error 1, handle it here without message

Case 2
'Expected error 2, handle it here without message

Case Else
'Abort or handle unexpected error
Wscript.Echo "Aborting from unexpected error " _
& Err.Number & " in ErrorSub1"
Wscript.Quit
End Select
Err.Clear
'continue script with error handling switched on
...

'Error handling no longer needed so switch it off
On Error GoTo 0
'If an error occurs here, WSH host provides error message
End Sub
--
Todd Vargo
(Post questions to group only. Remove "z" to email personal messages)
Paul Randall
2008-02-04 13:44:39 UTC
Permalink
Post by Todd Vargo
Post by Paul Randall
Here is a short script that demonstrates a few effects of
VBScript's
error handling. One problem I find while writing this kind of thing
is documenting it. Adding comments to the script, or echoing more
information can lead to a less understandable script. And a
separate
text document to explain what is happening doesn't work well
without
line numbered source code to refer to.
'Simple non-exhaustive test of 'On Error Resume Next'
' on subroutine calls.
Option Explicit
On Error Resume Next
Wscript.Echo "Started script"
ErrorSub1
Wscript.Echo "Wscript.Echo 1 - Back in Main from ErrorSub" &
Err.Number
Err.Clear
ErrorSub2
Wscript.Echo "Wscript.Echo 2 - Back in Main from ErrorSub" &
Err.Number
Err.Clear
ErrorSub3
Wscript.Echo "Wscript.Echo 3 - Back in Main from ErrorSub" &
Err.Number
Err.Clear
WScript.Echo "Reached end of script"
WScript.Quit
Sub ErrorSub1()
WScript.Echo "Entered ErrorSub1"
Err.Raise 1
Wscript.Echo "This statement never executed - Exitting Sub1"
End Sub
IMO, this code demonstrates how NOT to implement error handling. One should
not rely on a single instance of OERN to handle every possible error within
the script. As the code above demonstrates, OERN does not function as one
might expect when carried into a sub routine. An OERN should be placed in
each of the sub routines to handle errors on a localized basis.
Sub ErrorSub1()
WScript.Echo "Entered ErrorSub1"
On Error Resume Next
{statement that raises an error}
Select Case Err.Number
Case 1
'Expected error 1, handle it here without message
Case 2
'Expected error 2, handle it here without message
Case Else
'Abort or handle unexpected error
Wscript.Echo "Aborting from unexpected error " _
& Err.Number & " in ErrorSub1"
Wscript.Quit
End Select
Err.Clear
'continue script with error handling switched on
...
'Error handling no longer needed so switch it off
On Error GoTo 0
'If an error occurs here, WSH host provides error message
End Sub
--
Todd Vargo
(Post questions to group only. Remove "z" to email personal
messages)
Thanks for the input, Todd

I agree, the code demonstrates how NOT to implement error handling in
most scripts. 'Good' error handling would prevent demonstrating
things that might happen with poor error handling in effect. And
there are cases where the effect of letting the system handle it is
exactly what you want to happen (who says VBScript can't do a
'goto'?).

I wanted the script to 1) illustrate how the position of the most
recently executed 'On Error Resume Next' affects which statement is
executed after an error is raised, 2) be easily understandable, and 3)
be a short read. I think your good error handling illustrates how
that could make it confusing as to what the set of 'non-error
handling' program lines is trying to do; it often takes 10 or 20 lines
of code to handle the various problems that may occur in one
statement.

-Paul Randall
Loading...