[Python-ideas] except expression

Chris Angelico rosuav at gmail.com
Wed Feb 19 02:08:52 CET 2014


On Wed, Feb 19, 2014 at 11:11 AM, Jan Kaliszewski <zuo at chopin.edu.pl> wrote:
> IMHO bare except is practically always a very bad practice unless the
> exception is immediately re-raised:
>
> try:
>     foo()
> except:
>     logger.exception('error:')
>     raise
>
> ...and AFAIK, up to now, nobody proposed any syntax that would make it
> possible to re-raise an exception in an except expression.
>
> Therefore I believe that bare except should *not* be allowed in
> except expressions at all.

Reraising inside an expression doesn't make a huge amount of sense. If
you want to do something and then reraise, what's the value of the
expression? Go statement-form and make it clearer.

But there are legit uses of broad except. One is to use the exception
itself as the value. (See Lib/imaplib.py:568, quoted in the examples.)
Another is for a "this must never fail" code like repr
(Lib/asyncore.py:482, the next example). Arguably both should be
catching Exception, not BaseException; but the recommendation to "log
it and reraise" should apply just as much to catching Exception as to
bare-excepting, as an unexpected TypeError or AttributeError could
indicate a significant bug.

IMO the validity of bare except in an expression should be based on
readability and bug-magnet possibility, not whether or not the
exception can be reraised.

ChrisA


More information about the Python-ideas mailing list