Page 155 -
P. 155

persistence





              When an exception is raised and handled by your except suite, the Python interpreter passes an exception object
              into the suite. A small change makes this exception object available to your code as an identifier:

                                                     Give your exception object
              except IOError as err:                 a name…
                     print('File error: ' + err)         …then use it as part of
                                                         your error message.


              But when you try to run your code with this change made, another exception is raised:


              Traceback (most recent call last):
                File "<pyshell#18>", line 5, in <module>                           Whoops! Yet another
                                                                                   exception; this time it’s a
                  print('File error:' + err)                                      “TypeError”.
              TypeError: Can't convert 'IOError' object to str implicitly



              This time your error message didn’t appear at all. It turns out exception objects and strings are not compatible
              types, so trying to concatenate one with the other leads to problems. You can convert (or cast) one to the other
              using the str() BIF:
                                                          Use the “str()” BIF to force the
              except IOError as err:                      exception object to behave like a string.
                     print('File error: ' + str(err))

                                                                             And you now get a specific error
              Now, with this final change, your code is behaving exactly as expected:
                                                                              message that tells you exactly
              File error: [Errno 2] No such file or directory: 'missing.txt'  what went wrong.




           Of course, all this extra logic is starting to obscure the
           real meaning of your code.
                                                                           Wouldn’t it be dreamy if there
                                                                           were a way to take advantage of
                                                                           these mechanisms without the code
                                                                           bloat? I guess it’s just a fantasy...








                                                                                      you are here 4    119
   150   151   152   153   154   155   156   157   158   159   160