Exception and finally question
bokr at oz.net
Sat Apr 26 03:54:06 CEST 2003
On Thu, 24 Apr 2003 16:10:18 -0700, Erik Max Francis <max at alcyone.com> wrote:
>Tung Wai Yip wrote:
>> How to I access the exception object in a handler?
>> raise NameError, 'HiThere'
>> except NameError:
>> #how to print the message 'Hi There' here?
> raise NameError, "Hi, there."
> except NameError, e:
> print e
>Note that e is actually the exception _object_, not just the string (or
>whatever other argument) it was constructed with:
>... raise NameError, "What's up, dog?"
>... except NameError, e:
>... print repr(e)
>... print str(e)
><exceptions.NameError instance at 0x815b3b4>
>What's up, dog?
Sometimes it's useful to print the specific exception name along with the message,
if you're catching more than one kind of instance, e.g.,
>>> def tex(ex):
... raise ex, 'a message'
... except Exception, e:
... print 'Exception "%s" message: "%s"' % (e.__class__.__name__, e)
Exception "NameError" message: "a message"
Exception "NotImplementedError" message: "a message"
Exception "IOError" message: "a message"
Hm, how would you catch all exceptions raised as strings (e.g., raise "ho", "hum")
and print both string and 2nd arg? Do I have to dig with inspect?
It might be convenient if the system would convert such exceptions to a standard one,
so we could write e.g.,
except OldStringException, e:
print e, e.args
and see the particular string and also a message arg.
More information about the Python-list