[Python-ideas] except expression

Andrew Barnert abarnert at yahoo.com
Wed Feb 19 06:06:09 CET 2014


From: Chris Angelico <rosuav at gmail.com>

Sent: Tuesday, February 18, 2014 7:37 PM


> On Wed, Feb 19, 2014 at 2:25 PM, Steven D'Aprano <steve at pearwood.info> 
> wrote:
>>  I think bare excepts were useful back in ancient days when you
>>  could raise strings, and they were caught by identity not value. But I
>>  think there is strong evidence that this was a mistake: raising strings
>>  was removed in Python 2.6, rather than waiting for Python 3000. I expect
>>  that most people don't even remember that you ever could write things
>>  like
>> 
>>      raise "This is an error"
>> 
>>  and thank goodness for that :-)
> 
> They were caught by identity? Ouch. Definite bug magnet. In that case,
> yeah, you'd normally want to just put a bare "except:" and then 
> decide
> what to do with the exception... only... a bare except can't capture
> the thing thrown, so how do you decide? IMO having to turn to
> sys.exc_info is wrong; you should be able to work within the construct
> of the try/except block.


As far as I know, wrong or not, that's how you had to do it. I worked on at least one project that actually used a bare except, fished the string out of exc_info, and then did regexp matching on it. Because some people are so clever they're stupid.

But anyway, string exceptions are long gone, and good riddance. If you really want the same functionality, you can do it much cleaner by just defining a trivial StringException class, doing raise StringException("This is an error"), and using "except StringException as e" and fishing the string out of e. Only a little bit more verbose than a bare except plus exc_info, and a lot cleaner and more readable…


More information about the Python-ideas mailing list