Is except: ... pass bad style?

Alexandre Fayolle alf at merlin.fayauffre.org
Fri Sep 10 04:12:42 EDT 2004


Le 09-09-2004, marduk <marduk at python.net> a écrit :
> I commonly use code like this
>
> try:
>     # call optional method
>     myobj.method()
> except AttributeError:
>     # no biggie
>     pass
>
>
> Occasionally I use pylint, which is a good tool, but in the above

Good idea, and thanks. :-)

> snippet pylint will complain that 'Except doesn't do anything'.  True,
> but is that bad style?  I know there are other ways of doing it, but
> of all the other "obvious" ones, this appears the most straight
> forward.

I was the one who originally asked pylint to report this construct,
after spending too many hours looking for a bug caused by an silenced
exception (for the record, the code was not written in Python, but in
Java)

This is a only a warning. It is easy to disable the report from the
command line (--disable-msg W0704) if it bothers you anyway.

My personal POV on the topic is that such blocks without a clear comment
(or an else: block) make it more difficult to read the code, as a
general rule, and should be avoided when possible, because the reader
has to find out why it is reasonable to ignore the exception.

"Errors should never pass silently.
 Unless explicitly silenced."
         -- Tim Peters' Zen of Python

I feel that explaining why you silenced the error is generally
a good idea too.

-- 
Alexandre Fayolle                              LOGILAB, Paris (France).
http://www.logilab.com   http://www.logilab.fr  http://www.logilab.org



More information about the Python-list mailing list