[Python-ideas] except expression
Steven D'Aprano
steve at pearwood.info
Wed Feb 19 00:34:09 CET 2014
On Wed, Feb 19, 2014 at 02:25:15AM +1100, Chris Angelico wrote:
> On Wed, Feb 19, 2014 at 2:13 AM, MRAB <python at mrabarnett.plus.com> wrote:
> > Another possibility would be to say that a bare except in an expression
> > catches only certain "expression-oriented" exceptions, e.g. ValueError.
> > The simplest way to do that would be to make them subclasses of an
> > ExpressionError class. The question then becomes one of which
> > exceptions are "expression-oriented"...
>
> Easier than fiddling with class inheritance would be to make
> ExpressionError into a tuple of exception types - at least for testing
> purposes. If this _is_ to be done, I would definitely advocate having
> that name (or some equivalent) as a built-in, so it's straight-forward
> to either manipulate it or use it in a statement-except. But you're
> absolutely right that the question of which ones are
> expression-oriented would be a big one. 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.)
Encouraging people to catch all sorts of unrelated errors which, if they
ever did occur, would absolutely definitely without a doubt represent an
actual bug in their code is a terrible, terrible idea.
If you wrote
1/x except CommonErrors: 0
expecting that x was a number, and IOError was raised, caught and
swallowed, wouldn't you rather know about it?
--
Steven
More information about the Python-ideas
mailing list