Page 129 -
P. 129

files and exceptions


          Take a pass on the error


           With this data (and this program), it is best if you ignore lines that don’t
           conform to the expected format. If the call to the split() method causes
           an exception, let’s simply pass on reporting it as an error.
           When you have a situation where you might be expected to provide code, but
           don’t need to, use Python’s pass statement (which you can think of as the
           empty or null statement.)

           Here’s the pass statement combined with try:



                                data = open('sketch.txt')



                                for each_line in data:
                                    try:
             This code is               (role, line_spoken) = each_line.split(':', 1)
              protected from            print(role, end='')
              runtime errors.
                                        print(' said: ', end='')
                                        print(line_spoken, end='')
                                    except:
                                                              If a runtime error
                                        pass                  occurs, this code is
                                                              executed.

                                data.close()




           Now, no matter what happens when the split() method is invoked, the
           try statement catches any and all exceptions and handles them by ignoring the
           error with pass.


           Let’s see this code in action.                                                     Do this!




                                                                                 Make the required changes
                                                                                  to your code in the IDLE
                                                                                 edit window.


                                                                                       you are here 4    93
   124   125   126   127   128   129   130   131   132   133   134