473,605 Members | 2,602 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How do I get info on an exception ?

Using Python 2.2.2,
I want to catch all exceptions from "socket.gethost byaddr(ip)"

From IDLE, I can generate:
socket.gethostb yaddr('1.2')

Traceback (most recent call last):
File "<pyshell#2 8>", line 1, in ?
socket.gethostb yaddr('1.2')
herror: (11004, 'host not found') <=== what I want when I catch

When I run this code:
try:
hostname, aliases, hostip = socket.gethostb yaddr(ip)
return (hostip, hostname)
except:
print sys.exc_info()
print sys.exc_type
return

The "print sys.exc_info()" gives-
(<class socket.herror at 0x00AE7AC0>,
<socket.herro r instance at 0x00C725C0>,
<traceback object at 0x00C73920>)

And the "print sys.exc_type" gives-
socket.herror

How do I get the "(11004, 'host not found')" part?
More importantly, where is the answer documented that I should
have looked?

Frank
Jul 18 '05 #1
10 6777
Frank wrote:
Using Python 2.2.2,
I want to catch all exceptions from "socket.gethost byaddr(ip)"

From IDLE, I can generate:
socket.gethostb yaddr('1.2') Traceback (most recent call last):
File "<pyshell#2 8>", line 1, in ?
socket.gethostb yaddr('1.2')
herror: (11004, 'host not found') <=== what I want when I catch

When I run this code:
try:
hostname, aliases, hostip = socket.gethostb yaddr(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.gethostb yaddr('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 && ma*@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
Jul 18 '05 #2
> How do I get the "(11004, 'host not found')" part?
More importantly, where is the answer documented that I should
have looked?


Look at the traceback module from the Python standard library. If you
just wish to print the exception, do the following:

import traceback

try:
nosuchobject
except:
traceback.print _exc()

HTH!

Heiko.
Jul 18 '05 #3
On Fri, 2003-07-18 at 01:33, Frank wrote:
Using Python 2.2.2,
I want to catch all exceptions from "socket.gethost byaddr(ip)"
From IDLE, I can generate:
socket.gethostb yaddr('1.2')
Traceback (most recent call last):
File "<pyshell#2 8>", line 1, in ?
socket.gethostb yaddr('1.2')
herror: (11004, 'host not found') <=== what I want when I catch

When I run this code:
try:
hostname, aliases, hostip = socket.gethostb yaddr(ip)
return (hostip, hostname)
except:
print sys.exc_info()
print sys.exc_type
return


try:
do exceptional stuff...
except Exception, e:
print e.args, dir(e)

Probably that information is just in e.args, but you can add other
attributes to exceptions, any of which should be revealed by dir(e).

Exceptions are poorly documented, so I don't know where that might be
noted.

Ian

Jul 18 '05 #4
On Thu, 17 Jul 2003 23:29:40 -0700, Erik Max Francis <ma*@alcyone.co m> wrote:
Frank wrote:
Using Python 2.2.2,
I want to catch all exceptions from "socket.gethost byaddr(ip)"

From IDLE, I can generate:
>>> socket.gethostb yaddr('1.2')

Traceback (most recent call last):
File "<pyshell#2 8>", line 1, in ?
socket.gethostb yaddr('1.2')
herror: (11004, 'host not found') <=== what I want when I catch

When I run this code:
try:
hostname, aliases, hostip = socket.gethostb yaddr(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.gethostb yaddr('1.2')
... except Exception, e:
.... print 'plain e:', e
.... print 'e class:', e.__class__
.... print 'e class name:', e.__class__.__n ame__
.... 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.gethostb yaddr('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('exception s') is also helpful (note quotes)

Regards,
Bengt Richter
Jul 18 '05 #5
In article <U2************ ***@nwrdny01.gn ilink.net>,
Raymond Hettinger <py****@rcn.com > wrote:
Jul 18 '05 #6
>>> >The list of possible socket exceptions is in the docs for sockets.
>It also describes the (errno, string) return tuple value of inst.args.
.
True.

But unsatisfying--at least to me.


Submit a patch.

.
.
I deserved that.

There was more to my post, of course. Part of what I was trying to
express is that exception interfaces are almost always relegated to
a footnote, with only a generalized description, even in the frequent
case that a method's exceptions are more complicated than its invoca-
tions.

Rather than tilt at the collection of all such windmills, I want to
first understand better why this is, and what response is appropriate.
To summarize: I don't know what patch is the right one. I also
thought it only fair to warn Mr. July that things are indeed more dif-
ficult than we were explaining, even though I didn't feel up to
detailing the difficulties.

So, Raymond, do you have general guidelines for how you think excep-
tions should be documented?


I don't know what Raymond will suggest, but for myself I always (well,
nearly always) when I find the docs insufficient, I'll submit a patch
which contains what I would like to read there.
Works pretty well so far...

Thomas
Jul 18 '05 #7
[Cameron Laird]
But unsatisfying--at least to me.
Submit a patch.

.
.
.
I deserved that.


It wasn't a jab.
Truly, if you see a way to clarify the docs, submit a patch.
If everyone finds it helpful, it will be accepted. That's how
the docs improve over time. I've personally written or
accepted over a hundred of these in the past year.

There was more to my post, of course. Part of what I was trying to
express is that exception interfaces are almost always relegated to
a footnote, with only a generalized description, even in the frequent
case that a method's exceptions are more complicated than its invoca-
tions.
No doubt, exceptions often get less explanation than everything else.
However, in this case, the docs seemed reasonably clear to me.

The part that could be improved is where it talks about returning a
message or a tuple, as if either one but not both could occur at any
time. It would be more accurate to say, that in all cases an exception
instance is returned; the instance has a __str__ method so it can be
printed as if it were a string; the instance has an attribute "args" which
is the tuple (errno, errmsg); and the instance has a __getitem__ method
so the args tuple can be directly unpacked as if the instance had been
the tuple itself.

OTOH, that is long-winded and distracts from the flow of knowledge
about sockets. It is also how all exception instances work.

So, Raymond, do you have general guidelines for how you think excep-
tions should be documented?


Unless there are interesting values being returned, it is probably
sufficient to name the exception, state what it represents, and
describe where it fits in the class structure (i.e. socket.herror is a
subclass of socket.error). When you think about it, why have
three paragraphs on an exception whose code is as simple as:

class xyzException(Ex ception): pass # raised when xyz occurs

When interesting values are returned, describe the meaning of
each element in the instance's arg tuple (i.e. (errno, errmsg)).
Afterall, the code behind it may be as simple as:

raise socket.herror(e rrno, errmsg) # reveal the packet's error information

Elsewhere in the docs, functions descriptions should list the names
of the exceptions they can raise unless it is obvious or pertains
to a whole collection of functions (i.e. all high-volume socket
operations can potentially raise a timeout).

In general, I like the documents to be as specific as possible without
replicating the code or locking in a particular implementation. However,
there is a competing force to keep module documents centered on how
to use the module. For example, I found the unittest documentation to
be highly specific and thorough, yet unsatisfactory because you practically
had to read a book on the subject to be able to make basic use of the
module. To fix it, I added a new introductory section that covers
(in one page) the 5% of the module that will meet 95% of your needs
(enough to get you up and running).
Raymond Hettinger
Jul 18 '05 #8
On Tue, 22 Jul 2003 17:59:48 GMT, "Raymond Hettinger"
<vz******@veriz on.net> wrote:
[Cameron Laird]
>> But unsatisfying--at least to me.
>
>Submit a patch.

.
.
.
I deserved that.


It wasn't a jab.
Truly, if you see a way to clarify the docs, submit a patch.
If everyone finds it helpful, it will be accepted. That's how
the docs improve over time. I've personally written or
accepted over a hundred of these in the past year.

There was more to my post, of course. Part of what I was trying to
express is that exception interfaces are almost always relegated to
a footnote, with only a generalized description, even in the frequent
case that a method's exceptions are more complicated than its invoca-
tions.


No doubt, exceptions often get less explanation than everything else.
However, in this case, the docs seemed reasonably clear to me.

The part that could be improved is where it talks about returning a
message or a tuple, as if either one but not both could occur at any
time. It would be more accurate to say, that in all cases an exception
instance is returned; the instance has a __str__ method so it can be
printed as if it were a string; the instance has an attribute "args" which
is the tuple (errno, errmsg); and the instance has a __getitem__ method
so the args tuple can be directly unpacked as if the instance had been
the tuple itself.

OTOH, that is long-winded and distracts from the flow of knowledge
about sockets. It is also how all exception instances work.

So, Raymond, do you have general guidelines for how you think excep-
tions should be documented?


Unless there are interesting values being returned, it is probably
sufficient to name the exception, state what it represents, and
describe where it fits in the class structure (i.e. socket.herror is a
subclass of socket.error). When you think about it, why have
three paragraphs on an exception whose code is as simple as:

class xyzException(Ex ception): pass # raised when xyz occurs

When interesting values are returned, describe the meaning of
each element in the instance's arg tuple (i.e. (errno, errmsg)).
Afterall, the code behind it may be as simple as:

raise socket.herror(e rrno, errmsg) # reveal the packet's error information

Elsewhere in the docs, functions descriptions should list the names
of the exceptions they can raise unless it is obvious or pertains
to a whole collection of functions (i.e. all high-volume socket
operations can potentially raise a timeout).

In general, I like the documents to be as specific as possible without
replicating the code or locking in a particular implementation. However,
there is a competing force to keep module documents centered on how
to use the module. For example, I found the unittest documentation to
be highly specific and thorough, yet unsatisfactory because you practically
had to read a book on the subject to be able to make basic use of the
module. To fix it, I added a new introductory section that covers
(in one page) the 5% of the module that will meet 95% of your needs
(enough to get you up and running).
Raymond Hettinger

Thanks to all for your help.

After checking that the input is a string, I try calling
gethostbyname/addr depending on whether the first char is numeric and
catch:
"except socket.error, err:"
Will this catch all possible errors? I've tried feeding various
errors into my def and caught them all so far. Input might come from
users at the keyboard, and crashing the program is not an option, no
matter what is typed in.
------------------------------------
I did look for the solution before posting; I checked:
Python Lib Ref 2.2.2
Python Language Ref 2.2.2
Lutz - Learning Python
Lutz - Programming Python, 2nd
Holden - Python Web Programming
Brueck - Python 2.1 Bible
Martelli - Python in a Nutshell
and even Guido's Tutorial. If the complete answer is there, I could
not find it or assemble all the parts from the various references.
Perhaps with more experience in Python it would have been clearer, but
I have to agree with those that say exceptions are not well
documented. Complete and precise documentation is probably more
important for a language/compiler/interpreter system than any anything
else.

Frank
Jul 18 '05 #9
On Tue, 22 Jul 2003 16:44:04 -0000, cl****@lairds.c om (Cameron Laird) wrote:
Raymond Hettinger <py****@rcn.com > wrote:
>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.
.
.
.
True.

But unsatisfying--at least to me.


Submit a patch.

.
.
.
I deserved that.

There was more to my post, of course. Part of what I was trying to
express is that exception interfaces are almost always relegated to
a footnote, with only a generalized description, even in the frequent
case that a method's exceptions are more complicated than its invoca-
tions.

Rather than tilt at the collection of all such windmills, I want to
first understand better why this is, and what response is appropriate.
To summarize: I don't know what patch is the right one. I also
thought it only fair to warn Mr. July that things are indeed more dif-
ficult than we were explaining, even though I didn't feel up to
detailing the difficulties.

So, Raymond, do you have general guidelines for how you think excep-
tions should be documented?


ISTM there are (at least) two important places for doc info: Code-associated and
language/tool-usage-associated. There are docs we approach as docs like books to read,
and there are embedded docs as in doc strings and comments. And pydoc sort of
bridges the gap and makes a book from code and whatall.

I wonder where the best place is to enhance the documentation accessible to users.
I suspect it would be in the area of pydoc and the structure of "code and whatall."
The most likely place to find up-to-date info is in the latest code. (See below
for an idea of how to enhance the latest code doc info without changing known-good
code source).

Exceptions (subject topic ;-) are a special case. In principle any code documentation
could be enhanced by adopting source conventions to help pydoc present better info.
The question then becomes how best to format the doc-enhancing info, where to put it,
and how best to support its presentation.

One thing that is a deterrent to improved documentation *within* code is that people
like to minimize the number of official code versions, whether by CVS or just noting
MD5 digests etc., and/or by burning an "official" CDROM. This makes me wonder if it would
make sense to have a way to store doc info separately, yet still integratable into a pydoc
presentation.

One way would be to have a file name convention, so that the optional doc-enhancement
info for e.g., xxx.py would be found in, e.g., xxx.dpy. This could make a clutter of small
files though, so maybe one or more .dpx files could contain the mapping from multiple
small related sources to a single .dpy. And by convention .dpy info for packaged files
would be looked for in a .dpy for the overall package if not found separately.

Ok, we could hone this search mechanism. What about the structure of .dpy files themselves,
which now potentially could have info enhancing docs for both xxx.py and yyy.py?

Some kind of easy internal labeled sections to separate xxx.py from yyy.py info
would seem obvious. Then, the real question: what goes in the .dpy section for xxx.py
so as to tie into certain parts of xxx.py code, without requiring changes to that code
(which, remember, may be on a CDROM etc)?

The context-finding mechanism of diff/patch would be one option, but to use that literally
would make the .dpy files into diff files, and probably not something easy to generate
manually and readably. And you don't want to carry a whole source fork just to maintain
doc enhancement .dpy files. So we need some conventions functionally to enable human-doable
doc diff patches. Maybe with special easy syntax to refer to exception raising loci
in the code vs catching, vs functions, classes, methods, existing doc strings, etc, etc.

An advantage of pure doc-enhancement info is that a mistake can't break the actual code,
so more people could be given commit privileges for that kind of files, if maintained
separately on CVS. Even wide-open wiki methods could be considered. You could even configure
pydoc to query python.org efficiently to check if a local cache is out of date, and prompt
for optional download.

But this is a matter of arriving at some PEP consensus after discussing 1) whether it's
worth discussing, and 2) what the usability goals are for both users and creators of
doc enhancement info, and 3) who has the time to follow up on stuff like this.
Just writing this post cost something, as will your replies (if any ;-)

Regards,
Bengt Richter
Jul 18 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1359
by: Jan Decaluwe | last post by:
Hi: There is a difference between exception info formatting by the interpreter versus the traceback module. For example, say we define an exception Error in file module.py: $ python Python 2.3 (#1, Sep 12 2003, 15:05:00) on linux2 Type "help", "copyright", "credits" or "license" for more information.
3
1374
by: lzh_gladiator | last post by:
Hello How can I get Current Thread Infomation about catched exception. Related Resource will be more helpful. Thanks in advance lzh_gladiator
5
3292
by: Samuel R. Neff | last post by:
When you have an unhandled exception in vb.net how do you view the exception information in the debugger? In C# the debugger creates a local variable that points to the exception and you can view it in one of the windows (autos or locals, don't remember which). That doesn't appear to be the case with vb.net. I also tried using the command window to inspect "Err" but that gave nothing useful (always empty).
20
4459
by: Tim Reynolds | last post by:
Team, I am developing a web service. In testing in on my enw PC, I am expecting to see exceptions thrown appear on my browser. Instead I am getting an HTTP 500 Internal Server Error page and I am not seeing my exception details. The web.config file being used has the setting <customErrors mode="Off"/>. This should allow me to see the detailed exception info. On a different computer - same code - same web config - the exception details...
4
3856
by: Darren Mar-Elia \(MVP\) | last post by:
So, I have my little .Net 2.0 C# utilities out in the wild and occasionally they have bugs(!). Often the bugs are easy to troubleshoot remotely but occasionally I would like to write detailed trace info to a simple text file that I could use to further track down the bugs. Additionally, somewhat related, it would be useful to be able to get the line number where an exception was thrown, which is slightly different than a debug log, but...
2
4249
by: Richard Coltrane | last post by:
Hi there, Ive just implemented some application level exception handling in ASP.Net 2.0. I deliberately set up a null reference error in my code to see how this would be handled. Sure enough the applicationOnError code runs in Global.asax and hands it off to my custom error page but theres no info in the exception returned by Server.Getlasterror. The type of this exception is just HttpUnhandledException (which is obvious,
2
1469
by: Paolo | last post by:
Hello Everybody! Considering this code: try { ExecuteOperation(); } catch {
0
1197
by: akash | last post by:
Hi, I've got some C# code instantiating a managed C++ class which in turn instantiates an unmanaged C++ class. I'm getting intermittent exceptions caught by my C# code, but the I can't get any details of the root cause. The info I have is: System.Runtime.InteropServices.SEHException was unhandled by user code ErrorCode=-2147467259 Message="External component has thrown an exception."
9
8598
by: Adem | last post by:
Is it possible to get some info about an unknown exception, ie. the "catch (...)" case below: catch (const blah1 &ex) { cout << "blah1 exception." << endl; } catch (const blah2 &ex) {
0
7999
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, weíll explore What is ONU, What Is Router, ONU & Routerís main usage, and What is the difference between ONU and Router. Letís take a closer look ! Part I. Meaning of...
0
7931
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8423
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8411
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8281
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5444
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3911
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
3956
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1530
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.