How do I find what kind of exception is thrown.

Ben Finney ben+python at benfinney.id.au
Tue Sep 5 18:59:36 EDT 2017


Antoon Pardon <antoon.pardon at vub.be> writes:

> Python 2.6.4 on a solaris box.
>
> I have a program in which all kind of excptions can be thrown and caugth.
> The main program is something like below:
>
> try:
>     do_stuff
> except Exception:
>     log unexpected trouble

You're throwing away the exception object, with the information you
need.

Instead::

    try:
        do_stuff()
    except Exception as exc:
        log_unexpected_trouble(exc)

> Now I found the following in the logs: [Errno 131] Connection reset by peer

That doesn't have the exception type in it. Probably because you are
logging only ‘str(exc)’, which returns the exception message.

If you *also* want the exception type to be logged, you'll need to get
at it.

You could use ‘"{0.__class__.__name__}: {0}".format(exc)’.

> This is a problem I would like to catch earlier however I have no idea
> what exception I would have to catch in order to treat this case.

Start by logging what exceptions actually occur, complete with their
types. Then, when you have more data, decide which ones you need to
handle specially and which ones can propagate normally.

-- 
 \       “An idea isn't responsible for the people who believe in it.” |
  `\                                      —Donald Robert Perry Marquis |
_o__)                                                                  |
Ben Finney




More information about the Python-list mailing list