Page 136 -
P. 136
keep it simple
You were to grab your pencil, then in box 1, write down what you
thought the program on the left does. In box 2, write down what
There’s a lot to write, so you actually need you thought the program on the right does.
more space for your description than was
provided on the previous page.
1 The code on the right starts by importing the “os” library, and then it uses “path.exists” to
make sure the data file exists, before it attempts to open the data file. Each line from
the file is then processed, but only after it has determined that the line conforms to the
required format by checking first for a single “:” character in the line. If the “:” is found,
the line is processed; otherwise, it’s ignored. When we’re all done, the data file is closed. And
you get a friendly message at the end if the file is not found.
Now…that’s more like it.
The code on the right opens a data file, processes each line in that file, extracts the data of
2
interest and displays it on screen. The file is closed when done. If any exceptions occur, this
code handles them.
Complexity is rarely a good thing
Do you see what’s happening here?
As the list of errors that you have to worry about grows, the complexity of
the “add extra code and logic” solution increases to the point where it starts
to obscure the actual purpose of the program.
This is not the case with the exceptions handling solution, in which it’s obvious
what the main purpose of the program is.
By using Python’s exception-handling mechanism, you get to concentrate on
what your code needs to do, as opposed to worrying about what can go wrong
and writing extra code to avoid runtime errors.
Prudent use of the try statement leads to code that is easier to read, easier
to write, and—perhaps most important—easier to fix when something goes
wrong.
Concentrate on what your code needs to do.
100 Chapter 3