Page 331 -
P. 331
making an exception
When it couldn’t write to the file,
the program threw an exception
What happens when an error occurs? Some errors are really bad: they cause
the program to crash. Other, less serious errors are known as recoverable: the
program can keep running, even though something went wrong. You can spot
these situations in your code, because most programming technologies throw
an exception when they occur.
Imagine a line of code that has a problem, such as the line that was trying
to write to the deliveries.txt file. Python will spot that the append
operation failed and, instead of running the rest of the code that follows,
Python abandons ship and skips out of the code completely. That’s what
throwing an exception means: the program doesn’t crash, but it abandons what
you were trying to do and tries to recover the situation:
Bang!
This line def save_data():
of code fileD = open("deliveries.txt", "a")
causes the fileD.write("Depot:\n")
exception
to be fileD.write("%s\n" % depot.get())
thrown. fileD.write("Description:\n")
fileD.write("%s\n" % description.get())
I‛m outta here!
fileD.write("Address:\n")
fileD.write("%s\n" % address.get("1.0", END))
depot.set("")
description.delete(0, END)
description.delete(0, END)
address.delete("1.0", END) All of this code
is skipped.
But why skip past the rest of the code? Why not keep on running? Generally,
that would be a bad idea. Once a line of code has gone bad, there’s no way of
knowing if it makes sense to keep running the code that follows. For example,
if the Head-Ex code can’t open the deliveries file to append to it, it makes no
sense to continue trying to write data to the unopened file!
In order to recover, you need to start running your code
from somewhere else.
296 Chapter 8 ½