Catching Custom Python Exceptions
Python is often described as a language which doesn’t “surprise” people with strange edge cases.
Here’s one for you. Don’t peek at the answer, and try to predict the result.
>>> class NewException(Exception): pass
...
>>> try:
... raise NewException, 'Error Message'
... except NewException, message:
... pass
>>> print message
???? you answer here
>>> print message.__class__
???? you answer here
I always thought that the second argument in the except statement tallies with the second argument in the raise statement.
However this is actually wrong. The second argument is actually an instance of the Exception class which was thrown.
>>> class NewException(Exception): pass
...
>>> try:
... raise NewException, 'Error Message'
... except NewException, message:
... pass
>>> print message
Error Message
>>> print message.__class__
__main__.NewException
>>> # observe that message is not a string!
>>> print message.args
('Error Message',)
Is there any reasons why it is done this way? A Python wart or because I should have read the manuals:
raise [expression ["," expression ["," expression]]]
- raise – re-raises the last expression that was active in the current scope
- raise MyException(“message”)
- raise MyException, “message” – “message” passed to constructor
- raise MyException, (“message”, “IO-882″) – (“message”, “IO-882″) passed to constructor
- raise MyException, None – constructor called without arguments
- raise …, …, traceback – reraises error transparently in an except clause
About this entry
You’re currently reading “ Catching Custom Python Exceptions ,” an entry on Chui's Counterpoint
- Published:
- 5.16.07 / 4pm
- Category:
- Python
4 Comments
Jump to comment form | comments rss [?] | trackback uri [?]