Page 134 -
P. 134

take it to another level


          …Or add another level of exception handling


           If you are a fan of the “handle exceptions as they occur” school of thinking, you’ll
           simply wrap your code within another try statement.

           Add another
          “try” statement.
                            try:
                                  data = open('sketch.txt')


                                  for each_line in data:
                                      try:
            As with the
            other program,                (role, line_spoken) = each_line.split(':', 1)
            all of this                   print(role, end='')
            code remains                  print(' said: ', end='')
             unchanged.
                                          print(line_spoken, end='')
                                      except:
                                           pass



                                  data.close()
           Give the user    except:
           the bad news.          print('The data file is missing!')













              Another quick test is required, this time with the version of your program that uses exception handling. Press F5 to
              give it a spin.
              >>> ================================ RESTART ================================
              >>>                                As expected, this version of the
              The data file is missing!           program handles the missing file, too.
              >>>






           98    Chapter 3
   129   130   131   132   133   134   135   136   137   138   139