[Python-ideas] except expression

Chris Angelico rosuav at gmail.com
Wed Feb 19 01:48:04 CET 2014


On Wed, Feb 19, 2014 at 10:34 AM, Steven D'Aprano <steve at pearwood.info> wrote:
>> I could imagine catching
>> (ValueError, Unicode{En,De}codeError, AttributeError, EOFError,
>> IOError, OSError, LookupError, NameError, ZeroDivisionError) and
>> that's just from a quick skim of the built-in names. Would you
>> consider making a tuple like that and then using "except
>> CommonErrors:" all over your code? Or more to the point, if it were
>> really convenient to do that, would it improve your code?
>
> I hope that you were making a reductio ad absurdum argument as to why
> this is a bad idea.
>
> Exception handlers should ALWAYS catch the FEWEST errors that you KNOW
> you need to handle. (Excuse my shouting, but this is important.)

Pretty much. I started out saying that it doesn't need to be a
superclass (thus there's no need to "infect" every exception
definition with this check), but by the time I'd written out that list
of stuff that would make sense to catch, it was pretty obvious that
such a diverse list would make a terrible default.

Also, compare this list against the first 125 lines of my stdlib
conversion examples (the "easy ones", the mostly-non-controversial
ones). Even ignoring the ones that are too broad for their needs,
there are some that legitimately catch Exception, TypeError,
StopIteration, and a custom error from the email module (which would
be reasonably well handled by a subclassing solution but not really
with the tuple). There's no way to restrict this without making it
simultaneously dangerous AND useless.

ChrisA


More information about the Python-ideas mailing list