Guy’s Scripting Ezine 15 – Error Handling

Guy’s Scripting Ezine No 15 – Error Handling Techniques

Contents Error Handling Techniques

This Week’s Secret

If there is one thing that I have learnt about computing it is this; users rarely do what you expect.  Dare I take this one step further and say that budding scripters do not often apply my scripts as I anticipate?  The greatest mismatch is when I design VBScripts for Windows 2003 with XP clients, only for them to fail on Windows 98 clients in NT 4.0 domains.  Your challenge is to guess what the users will do, meanwhile, my challenge is to anticipate problems with non XP clients.

Guy Recommends: The Free IP Address Tracker (IPAT) IP Tracker

Calculating IP Address ranges is a black art, which many network managers solve by creating custom Excel spreadsheets.  IPAT cracks this problem of allocating IP addresses in networks in two ways:

For Mr Organized there is a nifty subnet calculator, you enter the network address and the subnet mask, then IPAT works out the usable addresses and their ranges. 

For Mr Lazy IPAT discovers and then displays the IP addresses of existing computers. Download the Free IP Address Tracker

Two scripting techniques

‘On Error Resume Next’ is like sticking your head in the sand.  This is the equivalent of ignoring the problem and hoping that the error is not serious and will go away.  ‘Option Explicit’ on the other hand, is like turning over a log and seeing what crawls out of the woodwork.  Option Explicit forces you to check explicitly that everything is as it should be and there are no hidden flaws.

On Error Resume Next

On Error Resume Next has two useful functions for logon scripts; firstly it suppresses error messages which could needlessly alarm users.  Secondly, it means the you can salvaging at least some of the valid commands on later lines in the script.

If you are going to use On Error Resume Next, then do place it on the first line of your script.  Where this on Error command comes into its own is if a server is down or a share is not available.  In the example below, the idea is that even if the first command to map a network drive fails, you want the script will carry trying to map other drives.

Example 1 On Error Resume Next

Instructions

  1. Copy and paste the script below into notepad.  Save the file with .vbs extension e.g. mapnetdrive.vbs
  2. Change objNetwork.MapNetworkDrive “P:” , “\\alan\Home”
    To a real server and share on your network
  3. Leave objNetwork.MapNetworkDrive “R:” , “\\banana\reports”

‘ VBScript to demonstrate On Error Resume Next
‘ VBScript to Map Network Drives assume one server is unavailable
‘ Guy Thomas January 2004

on Error Resume Next
‘Set WshShell = WScript.CreateObject(“WScript.Shell”)
Set ObjNetwork = WScript.CreateObject(“WScript.Network”)

objNetwork.MapNetworkDrive “R:” , “\\banana\reports”
objNetwork.MapNetworkDrive “P:” , “\\alan\Home”

Note 1: Once the script works without error, try removing this line on
on Error Resume Next ‘ Rem out the line with an apostrophe if you prefer.

Solutions to real life Error Codes generated by this type of logon script

80070043 The network name cannot be found (Mistyped Server, or Share name)
80070055 The local device name is already in use (Already used drive Letter)
8007007B The filename, directory or volume is incorrect (Missing a parameter)
800704B0 The specified device name is invalid (Check the colon, H: not H for drive letter)
800704B3 No network provider accepted the given network path
80070709 The Printer name is invalid
80070761 The Network connection has files open or requests pending
80071329 Object Already Exists
8007202B A referral was returned from the server
80072030 There is no such object on the server
8007203A The server is not operational

For more errors codes – check here

Option Explicit

Where you need to check for logic errors and to make sure that you have declared all you variables, insert Option Explicit at the start of your script.

To see the effect I have a non Windows VBScript example. The purpose of my VBScript converts Celsius (Centigrade) into Fahrenheit. The learning point is to see how a logical error creeps in if I do not use Option Explicit. What happens is the script executes, you get an answer but the result is incorrect.

Example 2 Option Explicit

Instructions

  1. Copy and paste, save as a .vbs file e.g. celsius.vbs
  2. Run the script and note the answer is always 32!
  3. To correct the script, Add Option Explicit to line 4.
  4. Eureka! Up comes an error message ‘Variable is Undefined DegreesCelsius’.
  5. Alter line 26 to intDegreesCelsius and see that it the VBScript now works correctly.

‘ VBScript to demonstrate Option Explicit
‘ VBScript to convert Celsius to Fahrenheit
‘ Guy Thomas January 2004
Dim intDegreesCelsius, intDegreesFahrenheit, intResponse

intResponse = inputbox(“Please type Temperature in Celsius.”, “Guy’s Temperature Demo”)

if isnumeric (intResponse) then
intDegreesCelsius = intResponse

else
Wscript.Echo ” Please Enter a Number rather than a letter”
Wscript.Quit

end if

intDegreesFahrenheit = ConvertToFahrenheit(intDegreesCelsius)

Wscript.Echo intDegreesCelsius & ” Centigrade converts to: ” & intDegreesFahrenheit _
& ” Fahrenheit”

Function ConvertToFahrenheit(ByVal intDegreesCelsius)

‘ Deliberate Guy Error in Next line intDegreesCelsius
ConvertToFahrenheit = (DegreesCelsius * (9/5)) + 32

End Function
Wscript.Quit

Note 1: Extra the error handling code (below) to cater for people entering letters instead of numbers.

if isnumeric (intResponse) then
intDegreesCelsius = intResponse

else
Wscript.Echo ” Please Enter a Number rather than a letter”
Wscript.Quit

Common errors and how to avoid them

So you have decided to correct errors. There are three places to look for problems with your scripts, syntax, runtime and logical errors.

Syntax

Breaches of syntax rules are easy to spot because the error message contains the offending bracket or punctuation mark. e.g. Expected ‘)’ or Expected ‘If’.   Moreover, syntax errors begin with 800Axxxx. There are 53 types of syntax errors and here are some of the common reasons for syntax violations.

  • Keyword misspelt
  • Wrong Datatype
  • Set ObjNetwork yes
  • Set intPeople x
  • Incorrect arguments
  • Wrong type of quotations marks brackets
  • Spelling of keywords e.g. mapnetqorkdrive

Runtime

  • Servers, shares or files not available or misspelt.
  • Operating system differences
  • Server cpu under stress
  • Occasionally, security preventing VBScripts running, or permissions on the resources.

Logic Errors

Check formula, add brackets where necessary. Remember that & (ampersand) joins text where as + adds numbers. Divide by zero is less likely in our types of scripts.

For more about code errors see here.

Defensive Programming

Classic case of investing a little time upfront, which then pays back later with interest. Even the simplest scripts benefit from error handling and debugging.

Use a naming scheme, preferably with Hungarian Variables e.g. begin with int, or str

Declare and initialize all variables.  Use Option Explicit.

Break a long script into sections, reuse chunks of code that you have already tested.

Look out for endless loops.

Perhaps the biggest mistake is to go for an ‘all bells and whistles’ script instead of getting a basic model working and only then adding extra components.

Summary

Go for that professional finish, declare variables, anticipate problems, add error handling code. Time spent on error handling will improve your understanding of what the script can and cannot achieve.

For more details on error codes – Error Codes

See more about VBScript error correcting codes

VBScripts  • 800 Code list  • Ezines  • Logon Scripts   • PowerShell ErrorAction   • Free Log Tool

Ezine 7 On Error Resume  •Ezine 15 Error Codes  • Ezine 33 Troubleshooting  • Free WMI Monitor

• Ezine 49 Errors  • Ezine 54 Error correcting  • Ezine 69 Option Explicit  • Ezine 71 On Error