How do I get info on an exception ?
Bengt Richter
bokr at oz.net
Fri Jul 18 16:08:37 EDT 2003
On Thu, 17 Jul 2003 23:29:40 -0700, Erik Max Francis <max at alcyone.com> wrote:
>Frank wrote:
>
>> Using Python 2.2.2,
>> I want to catch all exceptions from "socket.gethostbyaddr(ip)"
>>
>> From IDLE, I can generate:
>> >>> socket.gethostbyaddr('1.2')
>> Traceback (most recent call last):
>> File "<pyshell#28>", line 1, in ?
>> socket.gethostbyaddr('1.2')
>> herror: (11004, 'host not found') <=== what I want when I catch
>>
>> When I run this code:
>> try:
>> hostname, aliases, hostip = socket.gethostbyaddr(ip)
>> return (hostip, hostname)
>> except:
>> print sys.exc_info()
>> print sys.exc_type
>> return
>
>Use the format:
>
> try:
> ...
> except ErrorType, e:
> ... do something with exception object e ...
>
Indeed. Or if you want to catch all standard exceptions until you know what is
happening, you could pick from the following. I guess you could also catch all
exceptions defined in a module without knowing what they're named, and re-raise
if other, e.g., with (untested!)
if not repr(e.__class__).startswith('socket'): raise
is there another way to do that?
>>> import socket
>>> try:
... socket.gethostbyaddr('1.2')
... except Exception, e:
... print 'plain e:', e
... print 'e class:', e.__class__
... print 'e class name:', e.__class__.__name__
... print 'vars keys:', vars(e).keys()
... print 'vars dict:', vars(e)
... print 'additional inherited clutter seen by dir:\n',dir(e)
...
plain e: (11004, 'host not found')
e class: socket.herror
e class name: herror
vars keys: ['args']
vars dict: {'args': (11004, 'host not found')}
additional inherited clutter seen by dir:
['__doc__', '__getitem__', '__init__', '__module__', '__str__', 'args']
You could also print a formatted vars(e) to see unanticipated attributes more nicely
with e.g., (untested!) print ''.join(['%16s = %r\n' %(k,v) for k,v in vars(e).items()])
>>>> import socket
>>>> socket.error
><class socket.error at 0x8154304>
>>>> try:
>... socket.gethostbyaddr('1.2')
>... except socket.error, e:
>... print e, dir(e), e.args
>...
>(1, 'Unknown host') ['__doc__', '__getitem__', '__init__', '__module__',
>'__str__', 'args'] (1, 'Unknown host')
>
>> How do I get the "(11004, 'host not found')" part?
>> More importantly, where is the answer documented that I should
>> have looked?
>
>Check the part on exception handling.
>
Interactively, help('exceptions') is also helpful (note quotes)
Regards,
Bengt Richter
More information about the Python-list
mailing list