The Most Diabolical Python Antipattern
Ian Kelly
ian.g.kelly at gmail.com
Fri Jan 30 04:11:36 EST 2015
On Thu, Jan 29, 2015 at 11:16 PM, Marko Rauhamaa <marko at pacujo.net> wrote:
> Ian Kelly <ian.g.kelly at gmail.com>:
>
>> At least use "except Exception" instead of a bare except. Do you
>> really want things like SystemExit and KeyboardInterrupt to get turned
>> into 0?
>
> How about:
>
> ==============================
> try:
> do_interesting_stuff()
> except ValueError:
> try:
> log_it()
> except:
> pass
> raise
> ==============================
Are you asking if I think this is better? It still swallows arbitrary
exceptions. Why would you want to re-raise the anticipated (and
logged) ValueError instead of the exception that could potentially be
unexpected?
> Surprisingly this variant could raise an unexpected exception:
>
> ==============================
> try:
> do_interesting_stuff()
> except ValueError:
> try:
> log_it()
> finally:
> raise
> ==============================
>
> A Python bug?
This does what it is supposed to. "If no expressions are present,
raise re-raises the last exception that was active in the current
scope." In this case, what that exception is depends on whether the
finally clause was entered as a result of an exception or fall-through
from the try clause. If you only want to re-raise the ValueError, then
use the first form above. If you only want to re-raise the other
exception, then do so from an except block (or don't catch it in the
first place).
More information about the Python-list
mailing list