Page 332 -
P. 332

exceptions and message boxes


           Catch the exception


           Python spots when an exception is thrown, and you can write some code to
           run when the exception occurs. This is called catching the exception. The code
           that you run when there’s an error resulting in the thrown exception is called
           an exception handler.


                                                                 Bang!
              def save_data():
                  fileD = open("deliveries.txt", "a")
                  fileD.write("Depot:\n")
                  fileD.write("%s\n" % depot.get())
                                                                                 OK, it says here I can
                  fileD.write("Description:\n")
                                                                                 recover by displaying
                  fileD.write("%s\n" % description.get())                        an error message, then
                  fileD.write("Address:\n")                                      restarting from this line
                                                                                 of code...
                  fileD.write("%s\n" % address.get("1.0", END))
                  depot.set("")
                  description.delete(0, END)
                  description.delete(0, END)
                  address.delete("1.0", END)                                                       Exception
                                                                 You can CATCH                     handling
                                                                 an exception.                     code.











                                                                                 A piece of code
           Creating exception handlers can really make life easy for your users. Instead
           of a flaky program that crashes or fails silently the first time something weird   that runs when
           happens, you can write programs that gracefully recover from errors. Exception
           handlers tidy up when something goes wrong and can even let your user   an exception is
           know that something strange happened.

           That’s what you need here: an exception handler that tells the user when   thrown is called an
           there’s a problem writing a delivery to the file.
                                                                                  exception handler.

           How are exception handlers written in Python?


                                                                                       you are here 4    297
   327   328   329   330   331   332   333   334   335   336   337