[Python-ideas] except expression

Chris Angelico rosuav at gmail.com
Tue Feb 18 16:40:50 CET 2014


On Wed, Feb 19, 2014 at 2:30 AM, Rob Cliffe <rob.cliffe at btinternet.com> wrote:
> Sorry, but this seems to me to be a futile discussion.
> Expressions can contain functions.
> Functions can raise any exception they like.
> So evaluating an expression can raise any exception you care to name.

Of course it could raise anything, but what are you likely to want to
catch and handle by returning a different value?

LookupError when your cache isn't populated
UnicodeDecodeError to fall back on a different encoding ("try UTF-8;
if that fails, assume the other end is Windows and try CP-1252" - I
have that logic in some places)
ZeroDivisionError and return float("inf"), float("nan"), or 0

But you wouldn't want to catch:

SyntaxError
ImportError
AssertionError
IndentationError
ProgrammerIsAMoronAndHisCodeIsInError

because most of them wouldn't come up in an expression context, and if
they do, you aren't likely to have a useful alternate value to return.

So it is conceivable that there be some tuple or superclass of "common
errors worth catching". Trouble is, it still often wouldn't be
appropriate to catch them all - maybe you want to hook into
LookupError, but accidentally catching a UnicodeDecodeError along the
way would mask a bug.

ChrisA


More information about the Python-ideas mailing list