Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > mertz@gnosis.cx

Reply
Thread Tools

mertz@gnosis.cx

 
 
Scott David Daniels
Guest
Posts: n/a
 
      01-02-2005
I was pointed to appendix A by a comp.lang.py post.
In the "except statements" section (which might better be called
the "try" statement and include a try: ... finally: ...), you say:

The 'except' statement can optionally bind a name to an exception
argument:

>>> try:

... raise "ThisError", "some message"
... except "ThisError", x: # Bind 'x' to exception argument
... print x
...
some message

String exceptions should not be encouraged (nor do I think they work).
Better code would be:

>>> class MyError(Exception): pass
>>> try:

... raise MyError, "some message"
... except MyError, x: # Bind 'x' to exception instance
... print x
...
some message

or, if you don't want two statements:

>>> try:

... raise ValueError, "some message"
... except ValueError, x: # Bind 'x' to exception instance
... print x
...
some message


The x, by the way, is bound to an instance of the class of the
exception, and it has a field "args" which will reflect the
arguments with which the exception was created. So in these
cases, x.args is ('some message',) and if the code were:

>>> try:

... raise ValueError("some message", 42)
... except ValueError, x: # Bind 'x' to exception instance
... print x
...
('some message', 42)

and x.args would be: ("some message", 42)


--Scott David Daniels
http://www.velocityreviews.com/forums/(E-Mail Removed)
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off




Advertisments