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:
This line def save data():
f C0de fileD = open("deliveries.txt", "a")
causes the exception to be thrown.
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)) depot.set("")
description.delete(0, END) description.delete(0, END) address.delete("1.0", END)
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.
Was this article helpful?