Datasheet

Chapter 1: A Quick Introduction to Programming
26
Expect the Unexpected
Always remember that anything that can happen probably will happen. The idea here is to code
defensively — preparing for the unexpected. You don’t need to become totally fixated on preparing for
all contingencies and remote possibilities, but you can’t ignore them either. You especially have to worry
about the unexpected when receiving input from the user, from a database, or from a file.
Whenever you’re about to perform an action on something, ask yourself questions such as:
What could go wrong here?
What happens if the file is flagged read-only?
What happens if the file isn’t there?
What happens if the user doesn’t run the program from the right folder?
What happens if the database table doesn’t have any records?
What happens if the registry keys I was expecting aren’t there?
What happens if the user doesn’t have the proper permission to carry out the operation?
If you don’t know what might go wrong with a given operation, find out through research or trial and
error. Get others to try out your code and get their feedback on how it worked for them, on their system
configuration, and on their operating system. Don’t leave it up to your users to discover how well (or
not) your script reacts to something unexpected. A huge part of properly preparing for the unexpected is
the implementation of proper error handling, which is discussed in detail in Chapter 6 .
Figure 1-8
c01.indd 26c01.indd 26 8/27/07 7:45:26 PM8/27/07 7:45:26 PM