Page 125 -
P. 125

files and exceptions


          Try first, then recover


           Rather than adding extra code and logic to guard against bad things
           happening, Python’s exception handling mechanism lets the error occur,
           spots that it has happened, and then gives you an opportunity to recover.
           During the normal flow of  control, Python tries your code and, if nothing goes
           wrong, your code continues as normal. During the exceptional flow of  control,
           Python tries your code only to have something go wrong, your recovery code
           executes, and then your code continues as normal.
                                                              Exceptional flow
                                                                                           Python tries
                 Normal flow                                                               your code, but
                                                                                           fails!


                                              Python tries
                                             your code.
                                                                                        Crash!
                                                                 Your recovery
                                                                  code executes.
                                                                                                 Your exception
                                     It’s all OK, so                                              is handled.
                                      keep going…




           The try/except mechanism                                                    Then you keep
                                                                                       going…
           Python includes the try statement, which exists to provide you with a way to
           systematically handle exceptions and errors at runtime. The general form of
           the try statement looks like this:
                         try:



          Both “try”
          and “except”                      your code (which might cause a runtime error)
          are Python
           keywords.
                          except:



                                            your error-recovery code


                                                                                       you are here 4    89
   120   121   122   123   124   125   126   127   128   129   130