Exception and finally question

Bengt Richter 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?
>> try:
>>     raise NameError, 'HiThere'
>> except NameError:
>>     #how to print the message 'Hi There' here?
>	try:
>	    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:
>>>> try:
>...  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):
 ...     try:
 ...         raise ex, 'a message'
 ...     except Exception, e:
 ...         print 'Exception "%s" message: "%s"' % (e.__class__.__name__, e)
 >>> tex(NameError)
 Exception "NameError" message: "a message"
 >>> tex(NotImplementedError)
 Exception "NotImplementedError" message: "a message"
 >>> tex(IOError)
 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.

Bengt Richter

More information about the Python-list mailing list