Page 333 -
P. 333
try to except
Watch for exceptions with try/except
In order to recover from an error as it happens, you need to indicate the code
that might throw an exception. In Python, you do this with try and except.
All you need to do is take the piece of potentially troublesome code and add
the try and except labels:
def save_data():
Note: this code
try: is indented
Put the exception under the “try”
handler labels around all statement.
fileD = open("deliveries.txt", "a")
of this code. fileD.write("Depot:\n")
fileD.write("%s\n" % depot.get())
fileD.write("Description:\n")
fileD.write("%s\n" % description.get())
fileD.write("Address:\n")
fileD.write("%s\n" % address.get("1.0", END))
If an exception is thrown
ANYWHERE in this depot.set("")
section, the computer will
description.delete(0, END)
jump to the code HERE.
description.delete(0, END)
address.delete("1.0", END)
Inside the handler, the exception is
except Exception as ex:
This is where the EXCEPTION assigned to a variable called “ex”.
HANDLER code goes.
If an exception is thrown between the try and except labels, the code
that follows the except label runs. The code that threw the exception
is abandoned. If no exception occurs, the code runs normally and the
code that comes after the except label is ignored.
Notice that the try/except labels are wrapped around all of the
function’s code. If there’s a problem opening the deliveries.txt
file, you don’t ever want to try writing to it. So, when trouble strikes,
you should adandon ship and skip to the code that tries to recover from
the error.
The code that then runs is the exception handler.
298 Chapter 8 ½