How do I get info on an exception ?

Raymond Hettinger vze4rx4y at verizon.net
Fri Jul 18 09:09:40 CEST 2003


"Frank" <Frank at home> wrote in message
news:fc07672ed11f5dcad539bcf9bf0d051f at news.1usenet.com...
> 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

> How do I get the "(11004, 'host not found')" part?

You could catch it with:

            except socket.herror, inst:
                  print inst.args

or more broadly with:

             except socket.error, (errno, string_message):
                   print code, message


> More importantly, where is the answer documented that I should
> have looked?

The list of possible socket exceptions is in the docs for sockets.
It also describes the (errno, string) return tuple value of inst.args.



Raymond Hettinger






More information about the Python-list mailing list