Tải bản đầy đủ (.pdf) (10 trang)

Microsoft WSH and VBScript Programming for the Absolute Beginner Part 32 pot

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (208.65 KB, 10 trang )

290
The Err object also provides two very useful methods. One of these methods is the Clear()
method. This method clears out or removes the previous error, ensuring that the next time
a script checks for an error, it will not get a false status (that is, it won’t see an already han-
dled error).
To use the
Clear() method, place it at the end of your error-handling routine, as demonstrated
in the previous example. VBScript automatically executes the
Clear() method on several occa-
sions, including
• Whenever the
On Error Resume Next statement executes
• Whenever an
Exit Sub statement executes
• Whenever an
Exit Function statement executes
The second
Err object method is the Raise() method. This method allows you to generate
error messages to test your error-handling routines. Without this method, the only way that
you could test your error-handling routines would be to deliberately introduce an error sit-
uation into your code. This method is easy to use, as demonstrated by the following:
Err.Raise(500)
For example, if you save the previous statement as a script and run it, you will see the error
message shown in Figure 9.8.
To use the
Raise() method, add it, along with the error number indicating the error that
you want to generate, just before the error-handling procedure that you want to test in your
script. After you have validated that the error handler is working as expected, remove the
Raise() statement from your VBScript.
Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition
Figure 9.7


A custom error
message
generated by a
VBScript error
handler.
Figure 9.8
Using the Err
object’s Raise()
method to
generate a
test error.
Reporting Errors
The best solution for errors is to prevent them from occurring in the first place; however,
that’s not always possible. The next best solution is to devise a way of dealing with errors,
whether it be handling them or simply ignoring them. Another option is to report errors by
recording them to a log file for later review. This allows you to come back and check to see
whether any errors have occurred. This is important because many time users do not report
errors when they occur, allowing errors to go on forever. By logging error messages, you create
an audit log that you can come back to and review from time to time to identify and fix any
errors that may have occurred.
When logging error messages, you have two options. The first option is to create your own
custom log file. The second option is to record error messages in the Windows application
event log. The second option, however, is only available if the script is running on a com-
puter running Windows NT, 2000, or XP.
Creating a Custom Log File
To create a custom log file, you must instantiate the FileSystemObject in your VBScript and
then use it’s
OpenTextFile() method to open the log file so that your script can write to it as
demonstrated in the following example.
On Error Resume Next

Err.Raise(7)
Set objFsoObject = WScript.CreateObject(“Scripting.FileSystemObject”)
If (objFsoObject.FileExists(“C:\ScriptLog.txt”)) Then
Set objLogFile = objFsoObject.OpenTextFile(“C:\ScriptLog.txt”, 8)
Else
Set objLogFile = objFsoObject.OpenTextFile(“C:\ScriptLog.txt”, 2, “True”)
End If
objLogFile.WriteLine “Test.vbs Error: “ & Err.Number & “, Description = “ & _
Err.Description & “ , Source = “ & Err.Source
objLogFile.Close()
In this example, the On Error Resume Next statement is used to allow the script to recover
from errors and the
Err.Raise(7) statement is used to simulate an “Out of memory” error.
291
Chapter 9 • Handling Script Errors
292
Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition
The rest of the script logs the error in a file called ScriptLog.txt, located on the computer’s
C: drive. If the file does not exist, it is created. Error messages are appended to the bottom
of the file each time they are written, allowing a running history of information to accu-
mulate. For more information about how to work with the
FileSystemObject and its methods
and properties, refer to Chapter 8, “Storing and Retrieving Data.”
You can adapt the previous example as the basis for developing an error-logging routine in
your VBScripts. Just copy and paste all but the first two lines into a function and call it when-
ever errors occur. Just make sure that you call the function before clearing the error. Alter-
natively, you can modify the example to use variable substitution and pass the function the
error number and description as arguments.
Be sure you always close any file that you open before allowing your script to
terminate. If you don’t, you may have problems with the file the next time you

want to open it because its end-of-file marker may be missing.
Recording an Error Message in the Application Event Log
An alternative to creating custom log files for your scripts is to record error messages in the
Windows application event log. This is achieved using the
WshShell object’s LogEvent()
method:
On Error Resume Next
Err.Raise(7)
Set objWshShl = WScript.CreateObject(“WScript.Shell”)
objWshShl.LogEvent 1, “Test.vbs Error: “ & Err.Number & “, Description = “ & _
Err.Description & “ , Source = “ & Err.Source
In this example, an “Out of memory” error has again been simulated, only this time, the
error has been written to the Windows application event log using the
WshShell object’s
LogEvent() method. Only two arguments were processed. The first is a number indicating
the type of event being logged. Table 9.5 lists the different types of events that are supported
by Windows. The second argument was the message to be recorded. Figure 9.9 shows how
the message will appear when viewed from the Event Viewer.
TRAP
Back to the Hangman Game
Now that you’ve reviewed the basic steps involved in overcoming VBScript errors, let’s return
to the Hangman game and begin its development. I’m going to cover the development of this
game from a different angle than in previous chapters. By now, you should have a pretty good
idea of how things work, and you should be able to read and understand the scripts that you’ll
see throughout the remainder of this book (just in case, I’ll leave plenty of comments in the
293
Chapter 9 • Handling Script Errors
Figure 9.9
Writing error
messages to the

Windows
application event
log using the
WshShell
object’s
LogEvent()
method.
Value Description
0 Indicates a successful event
1 Indicates an error event
2 Indicates a warning event
4 Indicates an informational event
8 Indicates a successful audit event
16 Indicates a failed audit event
TABLE 9.5 EVENT LOG E RROR I NDICATORS
294
code to help you along). This time, I’ll provide a much higher explanation of what is going on
and offer suggestions for ways to test and develop this script one step at a time. I’ll also point
out techniques that you can use to test and track the results of functions within the script, so
that you can validate their operation without having to first complete the entire script.
Designing the Game
The overall design of the Hangman game is fairly complex. To simplify things, I’ll begin the
game-development process by designing a flowchart, shown in Figure 9.10, which breaks
the game down into distinct units, each of which is responsible for performing a unique task.
Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition
Figure 9.10
A flowchart
providing a
high-level design
for the Hangman

game.
In addition to the Initialization Section and Main Processing Section, this script is made up
of 13 separate procedures. Therefore, you will develop this game in 15 steps, as follows:
1. Create a new script, adding your VBScript template and defining the variables,
constants, and arrays that are used by this script.
2. Develop the controlling logic for the Main Processing Section.
3. Using the
DoYouWantToPlay() function, create an introductory game splash screen and
determine whether the user wants to play.
4. Assign a list of game words to an array using the
FillArray() function.
5. Create a loop in the
PlayTheGame() function that controls the actual flow of the
game, collecting player guesses and calling other functions as required.
6. Retrieve a randomly selected game word using the
RetrieveWord() function.
7. Display space-separated underscore characters representing each letter in the game
word using the
InitialDisplayString() function.
8. Using the
FirstLevelValidation() function, validate the player’s input to make sure
the player is providing valid guesses.
9. Using the
SecondLevelValidation() function, test to determine whether the player
has already tried guessing a letter before accepting it as input.
10. Using the
TestLetterGuess() function, check to see whether the player made an
incorrect guess.
11. Using the
NonGuessedString() function, create a temporary string blanking out the

letters correctly guessed by the player.
12. Using the
CheckIfGameWon() function, check to see whether the player has guessed all
the letters that make up the mystery word.
13. Using the
FlipString() function, spin through the script created in step 11, and reverse
the display of each character of the string (that is, now only show the correctly guessed
letters).
14. Tell the player whether he or she won or lost using the
DisplayGameResults() function.
15. Display information about the game as it finishes using the
SplashScreen() function.
Setting Up the Script Template and Initialization Section
This portion of the script, shown here, should look pretty familiar to you by now, and does
not require much explanation. As you can see from the code, this section consists of the
script template and the definition of the script’s constant, variables, and array.
295
Chapter 9 • Handling Script Errors
296
‘*************************************************************************
‘Script Name: Hangman.vbs
‘Author: Jerry Ford
‘Created: 02/30/02
‘Description: This script demonstrates how to create a game of Hangman
‘ using VBScript and the WSH.
‘*************************************************************************
‘Initialization Section
Option Explicit
Const cTitlebarMsg = “VBScript HANGMAN”
Dim strChoice, strGameWord, intNoMisses, intNoRight, strSplashImage

Dim intPlayOrNot, strMsgText, intPlayAgain, strWrongGuesses
Dim strRightGuesses, blnWordGuessed, intLetterCounter
Dim strTempStringOne, strTempStringTwo, strWordLetter, strDisplayString
Dim intFlipCounter, intRandomNo, strProcessGuess, blnGameStatus
Dim strCheckAnswer
Dim astrWordList(9) ‘Define an array that can hold 10 game words
Putting Together the Logic for the Main Processing Section
Like the other scripts that you have seen in this book, the logic located in the script’s Main
Processing Section is very straightforward. It calls upon procedures that determine whether
the user wants to play, loads the game words into an array, starts the game, and ultimately
ends the game by displaying a splash screen and executing the
WScript.Quit() statement.
‘Main Processing Section
intPlayOrNot = DoYouWantToPlay()
If intPlayOrNot = 6 Then ‘User elected to play the game
FillArray()
PlayTheGame()
End If
SplashScreen()
WScript.Quit()
Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition
297
Chapter 9 • Handling Script Errors
At this point in the script, you have enough code in place to run your first test
and see whether there are any syntax errors. For now, I recommend that you go
ahead and define a procedure for each of the preceding functions, placing a
MsgBox() function that simply displays the name of the function inside each
one. Save and execute the script and make sure that the pop-up dialogs all
appear when they should. You can leave the functions as they are until you are
ready to complete them.

Using the
WScript.Quit() method, as I did in this section, is not required. Script
execution would have ceased after the display of the splash screen anyway. I
added this statement for the sake of clarity, and to prevent any statements that
I might have inadvertently left outside of a function in the Procedure Section
from accidentally being executed.
Building the DoYouWantToPlay() Function
You’ve seen functions very similar to this one in previous chapters. All the DoYouWantToPlay()
function does is display a clever graphic and ask the user if he or she wants to play a game
of Hangman.
Function DoYouWantToPlay()
‘Display the splash screen and ask the user if he or she wants to play
‘Display the splash screen and ask the user if he or she wants to play
strSplashImage = Space(100) & “***********” & vbCrLf & _
“W E L C O M E T O “ & Space(68) & “*” & Space(18) & “*” & _
vbCrLf & Space(100) & “0” & Space(18) & “*” & vbCrLf & _
“V B S c r i p t H A N G M A N !” & Space(50) & “—||—” & _
Space(15) & “*” & vbCrLf & Space(99) & “/” & Space(1) & “\” & _
Space(17) & “*” & vbCrLf & Space(120) & “*” & vbCrLf & Space(120) & _
“*” & vbCrLf & space(113) & “ ******* “ & vbCrLf & _
“Would you like to play a game?” & vbCrLf & “ “
DoYouWantToPlay = MsgBox(strSplashImage, 36, cTitlebarMsg)
End Function
This is a good place to pause and perform another test of your script to ensure that this func-
tion looks and works like it should. This test allows you to evaluate the operation of all the
controlling logic in the Main Processing Section.
TRICK
TRICK
298
Building the FillArray() Function

The FillArray() function, shown next, simply loads a list of words into an array. Later,
another procedure will randomly select a game word from the array.
Function FillArray()
‘Add the words to the array
astrWordList(0) = “AUTOMOBILE”
astrWordList(1) = “NETWORKING”
astrWordList(2) = “PRACTICAL”
astrWordList(3) = “CONGRESS”
astrWordList(4) = “COMMANDER”
astrWordList(5) = “STAPLER”
astrWordList(6) = “ENTERPRISE”
astrWordList(7) = “ESCALATION”
astrWordList(8) = “HAPPINESS”
astrWordList(9) = “WEDNESDAY”
End Function
You can’t perform much of a test on this function at this point, but you can always save and
run the script again to see whether you have any syntax problems. You should create a tem-
porary script, copy this function into it, and then create a
For Next loop that processes
and displays the contents of the array to ensure that the function is loading as expected.
Next delete the
For Next loop and add the following statements to the beginning of the
temporary script:
Dim astrWordList(9) ‘Define an array that can hold 10 game words
FillArray()
Save this script again. A little later, I’ll show you how to modify and use this temporary
script to perform another test.
Building the PlayTheGame() Function
The PlayTheGame() function, shown next, controls the play of the Hangman game. When I
developed this function, I wrote a few lines, stopped and tested it, and then wrote some

more. Specifically, each time I added a call to an external function I stopped, wrote the func-
tion that I called, and then did a test to be sure that everything worked before continuing.
However, it would take me too long to guide you through every step along the way. Instead,
Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition
I’ll leave it up to you to follow this basic process, and will instead focus on the development
of the other functions that make up the script, most of which are called from within the
PlayTheGame() function.
Function PlayTheGame()
‘Initialize variables displayed by the game’s initial pop-up dialog
intNoMisses = 0
intNoRight = 0
strWrongGuesses = “”
strRightGuesses = “”
‘Get the game a mystery word
strGameWord = RetrieveWord()
‘Call function that formats the initial pop-up dialog’s display string
strDisplayString = InitialDisplayString()
strTempStringOne = strGameWord
‘Let the player start guessing
Do Until intNoMisses = 6
‘Collect the player’s guess
strChoice = InputBox(vbCrLf & vbTab & strDisplayString & vbCrLf & _
vbCrLf & vbCrLf & “No. of Misses: “ & intNoMisses & _
“ “ & vbTab & “Incorrect:” & strWrongGuesses & vbCrLf _
& vbCrLf & vbCrLf & _
“Type a letter and click on OK.” , cTitleBarMsg)
‘Determine if the player has quit
If strChoice = “” Then
Exit Function
End If

strProcessGuess = FirstLevelValidation()
299
Chapter 9 • Handling Script Errors

×