When is bare except: justified?
dave at pythonapocrypha.com
Fri Dec 5 18:43:43 CET 2003
> When *is* it justified to use except:, then?
> I've seen simple uses like this that seem fine (this one from Alex
> Martelli, I think):
[snip: example where code is probably too simple to contain a bug]
> Another reasonable use, in a straightforward debugging hack:
> # use traceback module here to print out some detail of the exception
> print "your plugin is buggy"
The rule of thumb I use is that a bare except is bad if it hides the fact that
an exception occurred. So, for example, using a bare except in code like this
for worker in workers:
It's considered "okay" because even though the code prevents the exception from
propagating, it doesn't lose record of the fact that something went wrong.
We use these catch-all bare excepts in production code all the time to contain
failures to as small an area as possible. One particular example where this is
critical is in one application where we have a larger framework that also runs
some custom code for each customer (like your plugin example). Although it's
code we develop and own, we still have catch-alls around their execution so
that the failure of one doesn't interrupt service of the others.
There are actually quite a few cases like this for us where the reasons for
partial failure are too many to enumerate, and we'd prefer to keep executing
because the cause of the failure may go away over time and/or partial failure
is preferrable to total failure.
More information about the Python-list