Python doesn't catch exceptions ?

Peter Otten __peter__ at web.de
Wed Feb 1 12:12:41 EST 2017


Ivo Bellin Salarin wrote:

> Hi all,
> 
> I have a curious problem with Python exceptions.
> 
> The following code doesn't catch HttpError:
> ```
> from server.libs.googleapiclient.errors import HttpError
> [..]
>     try:
>         OAuth.backoffExec(request)
>         return True
>     except HttpError as e:
>         return e.resp.status == 404
>     except Exception as e:
>         import inspect
>         import os
>         logging.error("caught exception: {}, defined in {}. we are in
> {}".format(
>             e.__class__.__name__,
>             inspect.getfile(e.__class__),
>             os.getcwd()
>         ))
>         logging.error("processed exception: {}, defined in {}.".format(
>             HttpError.__name__,
>             inspect.getfile(HttpError)
>         ))
>         logging.error('e is an HttpError? {}'.format(isinstance(e,
> HttpError)))
> ```
> 
> This code generates instead the messages:
> ```
> ERROR 47.135[bigquery.py.create_table:362] caught exception: HttpError,
> defined in server/libs/googleapiclient/errors.pyc. we are in
> /Users/nilleb/dev/gae-sample-project/app
> ERROR 47.135[bigquery.py.create_table:366] processed exception: HttpError,
> defined in
> /Users/nilleb/dev/gae-sample-
project/app/server/libs/googleapiclient/errors.pyc.
> ERROR 47.136[bigquery.py.create_table:368] e is an HttpError? False
> ```
> 
> I haven't joined the paths in the messages above, but they are identical
> if I do that manually:
> 
> ```
> /Users/nilleb/dev/gae-sample-
project/app/server/libs/googleapiclient/errors.pyc
> /Users/nilleb/dev/gae-sample-
project/app/server/libs/googleapiclient/errors.pyc
> ```
> 
> Any ideas about how to diagnostic what's going wrong?

Make sure your program starts from scratch. There may be a "helpful" 
reload() that leaves the server in an inconsistent state. Here's a demo:

$ cat reload_demo.py
import binhex
from binhex import Error

for message in ["first", "second"]:
    try:
        raise Error(message)
    except binhex.Error as err:
        print "caught", err
    reload(binhex) # this creates a new Error class which will not be caught
$ python reload_demo.py
caught first
Traceback (most recent call last):
  File "reload_demo.py", line 6, in <module>
    raise Error(message)
binhex.Error: second





More information about the Python-list mailing list