Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

"on eror resume next" and "option explicit"

Status
Not open for further replies.

wveldeman

MIS
Jan 21, 2004
3
BE

As a relative novice in Vbscript I am rather surprised on the number of scripts one crosses in which "on error resume next" and "option explicit" are combined at the start of the script.
The first statement indeed hides the errors caused by using non-declared variables.
One can of course play around wtih these statement - by putting them off and on again - but I wonder if there is no more intelligent way of using both these -in itself- helpfull statements.
 
The On Error Resume Next is effective during Run time.
The Option Explicit is effective during Compile time.
So you get an error when you don't have Dim'ed a variable, even with the 2 above statements at the beginning of your script.
Furthermore, the Error handling is distinct for each Sub or Function.

Hope This Help, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884
 
as PH has intimated, if you use On Error Resume Next in your main script you should also put it in your subs and functions else you will scratching your head as well as your arse ;-)
 
Caution: Opinionated opinion ahead!

The reality is even a bit goofier than already described.

For example [tt]Option Explicit[/tt] is partially compile time, partially run time.

This and the reasons behind it can be found at Let's Get Explicit!. This guy wrote much of the code in the Microsoft Script Engines, so he ought to know.

The basic idea is that you can destroy the full value of [tt]Option Explicit[/tt] by setting [tt]On Error Resume Next[/tt] globally.

But a script should never be written with [tt]On Error Resume Next[/tt] at the head (and at the head of every procedure - Sub or Function). There isn't any legitimacy to this. What would it buy you?

Basically you are telling the Script Engine "ignore any exception, just try to keep on running the code."

In reality, in VBScript you use [tt]On Error[/tt] to implement a "try/catch" mechanism for errors you want to handle in your code instead of just having the script blow up.

Example:
Code:
    :
On Error Resume Next
objRS.Open strSQL, strCon1, adOpenForwardOnly
If Err.Number <> 0 Then
  On Error GoTo 0
  objRS.Open strSQL, strCon2, adOpenForwardOnly
End If
On Error GoTo 0
    :
This contrived example tries to open a recordset to one server defined by the ADO connection string contained in strCon1, and if it fails then it tries to open the recordset to another server as defined in strCon2.

In other words, the script has a reason to trap the exception.

Note that once the operation we want to trap exceptions on has completed (or failed) we shut off error trapping. That's because we want any further exceptions in the script (including a failure to connect the second time) to abort the script and inform the user.


I welcome alternative opinions, I'm always glad to learn something new.
 
hmm good point dilettante and i agree with your opinion.
however, by only using 'on error resume next' where you 'think' an error is going to occur you imply that you know that the rest of your code is so well constructed that an error wont occur or more precisely you have white-box tested the script completely. i am not sure all of us can say that about our code :)

most of the scripts i write execute on 7000 odd clients and i confess that i always declare 'on error resume next' in all my subs and at the head of the script. i do however turn it off sometimes in sections for testing.
i prefer the safety of knowing the script will execute and complete (possible with failures) without the need for user intervention.

but, to get back to your point, i agree with you. in an ideal world a script should not need to have 'on error resume next' declared at the head of the script.

regards,
richard
 
This guy who entered the question being a rookie, he/me was kind of knocked down by the first reply (thank you anyway for it). It sounds so simple - but I just don't experience it that way.

Like richard i have to trap as much as possible errors -even those I don't expect - and do some error treatment on them. Support people have to be able to see what's happening for instance by checking log files - end users should only receive things that works, or stuff that as far as they can judge doesn't do anything at all.

Once a script is ready for production I turn off the "option explicit" line - so that 's fine. But during the editing and the debugging it is handsome to have it.

I created this stupid little sample to demonstrate what is annoying me with this:


Option Explicit
On Error Resume Next
Dim var2
'I "forget" to declare var1

WScript.echo var1
var2=1
If var2=1 then Err.Raise(100)
wscript.echo Err.number


When editing and testing this script it would be sandsome if i can at the same time
- detect missing variable var1
- test that the error treatment i created for var2 is ok

With error resume next turned on: I don't trap the missing variable.
With error resume next turned off: I can't test the error handling 'cause I am throwed out before (no problem here but the majority of scripts tend to be slightly more complex).

Remark that the declaration of the variable and the error condition I volontary want to trap are in one single module - eventually a error wrapper or so can be added in a additional module.

This is not blocking it all - I just feel aesthetically offenced seeing lots of samples and guidelines around that in fact don't seem to work for me.
 
i might be wrong but in some languages the use of 'Option Explicit' will result in faster execution? so its not just useful for finding declaration mistakes but also improves performance?? perhaps i am wrong?

i sympathise with you wveldeman as i get the same thing.

i guess its an issue with Vbscript compiler i.e. you would like it to:

at runtime if you have Option Explicit turned on it should always flag up if you are using a variable which isnt declared even if you have On Error Resume Next activated as well
 
I guess I'm confused.

If you don't have Option Explicit, you are letting bugs exist in your script but suppress their detection. Then your script will likely operate incorrectly but nobody will ever understand why.

If you set On Error Resume Next you are doing very much the same thing, but for most other types of errors that would end up throwing an exception.

So, instead of "handling errors" at all, you are simply hiding errors (such as bugs) - and forcing users to live with incorrect results. When you actually check Err.Number for a non-zero value you may pick up an error here and there, but it could be from any code you executed along the way.

If you have Option Explicit and you turn on error-suppression (use On Error Resume Next) the interpreter will NOT catch undeclared items. This is according to Eric Lippert at least. I need to try this out myself.
 
Hello all,

I take a very liberal view on the option explicit in vbscript---you take the freedom and bear the consequence. One does all the times quick throw-away scripts for quick development---without sacrificing the float of impeccable logic---, and scripting is good for that. After,... you do whatever to make it look better. If the script gets bigger, you will voluntee to subject to its discipline because the return is obvious.

I have much stronger opinion on the on error resume next. Without the intention of error-trapping and graceful-exit in mind of the scripter, blanket <on the error resume next> is not only harmful and, when think of it, is really ridiculous. My self-imposed discipline is not to insert any of it except the place where legitimate runtime error may arise, handle the error and re-impose <on error goto 0> soonest possible. (Image you do jscript with try on the whole script without catch, does it make sense?) Unfortunately, it seems such practice do appear in quite a few technical books.

regards - tsuji
 
dilettante, i think all the statements you made are correct.

i wouldnt say that

""So, instead of "handling errors" at all, you are simply hiding errors (such as bugs) - and forcing users to live with incorrect results. When you actually check Err.Number for a non-zero value you may pick up an error here and there, but it could be from any code you executed along the way.""

is a negative thing. It simply means you have to make sure that you blackbox test your script fully. so, given all the possible input criteria the user gets out what they expect.

all that being said i would kill anyone who wrote a script which didnt finish executing under 'normal' circumstances because 'On Error Resume Next' had been turned off


 
So clearly the issue raises a few emotions. I sort of expected that. ;-)

example.vbs
Code:
Option Explicit
On Error Resume Next
Dim Something

Somthing = 12 'Oops, typo here!
Something = Something / 2
MsgBox CStr(Something)
The example above has a typo, but the use of an undeclared variable throws no exception.

The MsgBox ends up displaying 0, not the desired result.

How is this a good thing again? As I said, I must be missing something. It looks like this script simply silently works incorrectly, thus misleading the user or performing unintended actions - possibly formatting the user's hard drive by accident, deleting a wrong folder, etc.
 
Hello again,

It goes without saying that the scripter should be shouldering the task of debugging. If a device helps, all the better. But, do not let the overhead hinder your creativity.

But, frankly, mrmovie, it should not be the primary goal, I would say not be a goal at all, of a script to execute to the end of it. The only goal is to execute and gets the intended job done correctly.

Worse is blaming this or that functionality of the script engine or the control does not work, be a bug, etc without properly debug the script by letting the on error resume next hanging up there!

regards - tsuji
 
do get me wrong people,
i do use On Error Resume Next whilst developing a script for the reasons already outlined by dilettante.

however, i know i am not perfect and i know that i will NOT test the script in every possible situation that it will be presented with. (i agree that it is mathamatically possible to test for every perm and combo but we all know this doesnt happen in practice)
therefore i know there is the possibility that it will fail in its life time. because of this i will NEVER release a script to be run on 7000 machines which has the possibility of throwing an error to the user. i would prefer to rely on good logging for detecting where the script failed to perform its intended task, rather than a miffed user.

technically On Error Resume Next is not required to be declared Globally.

on a released script i would ALWAYS include it.

this thread has been interesting. :)
 
I'm very intrigued mrmovie.

How do you make this all work then? Once you have done an On Error Resume Next, all error notices are suppressed until something resets this state (On Error GoTo 0, or procedure exit).

When this is in effect, you need to sprinkle your code very liberally with tests of Err.Number or else you let errors slide by (as far as I know). If you choose to "log the errors" instead of interrupting the script after a notice to the user (wscript) or "caller" (cscript) errors will be lost unless you are careful to continually and repeatedly test and re-test Err.Number. Of course in ASP/IIS there are other options available to control what gets reported back to the user.

I'm just curious how you accomplish your goal in a released script, without the potential of ignoring unanticipated errors and inadvertantly producing incorrect results or actions.

I feel like I am missing something important.
VB has "On Error GoTo <err_handler_label>" but there is nothing like this in VBScript.
 
hmm i walked into this one i think.

i see the use of On Error Resume Next in a released script as a method of suppressing 'squiffy' errors (this prevents user interaction/intervention.)

Yes, all error messages are suppressed and i think that is the pin of my argument (not that i really had one!!! i dont mind playing the devils advo). If you do not put On Error Resume next in a released script the 'squiffy' error trapping is a script engine generated MsgBox to the user. What kind of error trapping is that?

I try and write my code so that it doesnt produce errors,

IsNull(), IsVariant(), Explicit String conversion, Explicit Ingeter conversion, checking if a key exists before attempting to add a key to a dictionary object, and all the other good coding practice i can pickup

If i know a method call has the potential to fail (WMI calls) then I check the Err.Number afterwards before acting on the Object i was expecting to get.

With the logging i implement after each Methods call i pipe the Err.Number and a description of what the attempted call was.

I am not perfect, I employ (what i consider) good error trapping and preventative checks in my code. But because i am not perfect I see that On Error Resume Next is a good safety net in a live environment.

I will finish with a question,

If you dont have On Error Resume Next declared is tsuji trying to say that a script execution is successful because it doesnt display an error message??? I think not.
 
Well I think we all have more to learn, and I value other perspectives. It may sound trite but the more I learn, the more I realize I don't know about things.

I believe tsuji and I are saying much the same thing, that simply suppressing exception notices is a bad policy. A script may appear to finish cleanly when in reality it failed or even "went off the rails" and did something bad.

This is very different from the idea of trapping errors and logging them instead of letting them blow up in the user's face. You just need to be sure you terminate the script early when something goes wrong, and this means you need to check Err.Number whenever you have On Error Resume Next.

But we're going in circles by now. My own next effort is going to be looking at VBScript's replacement: VB.Net.

While WSH is going to be around for awhile yet, I'm seeing more and more of a push for VB.Net as a replacement for VB programs, Office extension and automation, ASP, and WSH scripts. There are even a couple of unofficial script hosts out for the latter purpose already.
 
dilettante,

Very much the same thing. I agree.

mrmovie,

With due respect, I confess I do not quite get what you make out of my two postings. I only blame myself for the lack of communicating skill and tact. As a professional, I think you know what you are doing; and that's fine for me.

regards - tsuji
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top