How do I get info on an exception ?

Erik Max Francis max at alcyone.com
Fri Jul 18 02:29:40 EDT 2003


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 ...

>>> 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.

-- 
   Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
 __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
/  \ It is human nature to think wisely and act foolishly.
\__/  Anatole France




More information about the Python-list mailing list