Exception and finally question
Erik Max Francis
max at alcyone.com
Thu Apr 24 19:10:18 EDT 2003
Tung Wai Yip wrote:
> How to I access the exception object in a handler?
>
> try:
> raise NameError, 'HiThere'
> except NameError:
> #how to print the message 'Hi There' here?
try:
raise NameError, "Hi, there."
except NameError, e:
print e
Note that e is actually the exception _object_, not just the string (or
whatever other argument) it was constructed with:
>>> try:
... raise NameError, "What's up, dog?"
... except NameError, e:
... print repr(e)
... print str(e)
...
<exceptions.NameError instance at 0x815b3b4>
What's up, dog?
> Why except and finally can't be used together? I like to log a error
> message if an exception is throw. And I a file to be guaranteed to be
> close. What can't I do them together?
By design. Originally, as I understand it, Python supported a unified
try: ... except: ... finally: ... construct, but evidently it caused a
lot of confusion with newbies (personally, I don't see where the
confusion would be, but I guess that's because I'm familiar with the
construct from Java). So in modern Python the try can either have an
except (perhaps several) or a finally, but not both.
You can get the effect you're probably looking for by just wrapping a
try: ... except: ... inside a try: ... finally: ...
try:
try:
somethingThatMayRaise
except ...:
handleErrorCaseOrMaybeReraise
finally:
doThisRegardless
--
Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
__ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/ \ Insight -- the titillating knack for hurting!
\__/ Colette
Blackgirl International / http://www.blackgirl.org/
The Internet resource for black women.
More information about the Python-list
mailing list