how to handle exceptions?

Alex Martelli aleaxit at yahoo.com
Mon Sep 11 07:00:14 EDT 2000


"Mike 'Cat' Perkonigg" <blablu at gmx.net> wrote in message
news:8FAC77A61mikecat at 192.168.10.38...
> Hi!
>
> If I want to print exceptions but not interrupt the program, how can I do
> that?

    try:
        somethingorother()
    except:
        print sys.exc_info()

e.g.:

>>> import sys
>>> try:
 x=1/0
except:
 print sys.exc_info()


(<class exceptions.ZeroDivisionError at 0082712C>,
<exceptions.ZeroDivisionError instance at 00B5B6DC>, <traceback object at
00B5B010>)
>>>

Of course, you can be more selective/refined in your printing!


> How can I get the exception value (traceback buffer)?

The exception value is the 2nd item in the triple returned by
sys.exc_info(), while the traceback object is the third one;
very different things!

The value is an instance of the exception class you caught,
and you probably want to call str() or it or access its
attribute .args:

try:
 x=1/0
except:
 print sys.exc_info()[1].args


('integer division or modulo',)

For the traceback, see the traceback module, and the example
at 3.9.1 in the docs...


Alex






More information about the Python-list mailing list