How do I find what kind of exception is thrown.

Peter Otten __peter__ at web.de
Tue Sep 5 06:05:33 EDT 2017


Antoon Pardon wrote:

> 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
> 
> Now I found the following in the logs: [Errno 131] Connection reset by
> peer
> 
> 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.
 
The logging package in the stdlib provides a way to include the traceback 
into the logfile:

$ cat log_exc.py
import logging

def do_stuff():
    1/0

logger = logging.getLogger()
logging.basicConfig(filename="tmp.log")

try:
    do_stuff()
except Exception:
   logger.exception("unexpected trouble")
$ python3 log_exc.py 
$ cat tmp.log
ERROR:root:unexpected trouble
Traceback (most recent call last):
  File "log_exc.py", line 10, in <module>
    do_stuff()
  File "log_exc.py", line 4, in do_stuff
    1/0
ZeroDivisionError: division by zero
$ 





More information about the Python-list mailing list