Should bare except statements be allowed in the Python stdlib?
Firstly to clarify the terminology, this is bare except statement:
try:
...
except:
...
And this is a non-bare except statement, but bear in mind the type of the exception that is caught can be anything:
try:
...
except Exception:
...
The point is that both fragments are a catch-all exception handler, only the second is slightly more better/restrictive since it won't catch a SystemExit
exception for example (which you rarely want to catch). This is obviously discussed before and even made it to a (rejected) PEP.
So I'm tempted to say that the stdlib should not use bare except statements. If you need to catch more then Exception
they can always catch BaseException
. However grepping the stdlib reveals 384 cases of bare except statements, to be fair many of these are in test cases but still.
The one that hurt me today was in socketserver.BaseServer.handle_request
, now I have to re-write the .handle_error()
function to call sys.exc_info()
and check that it's a subclass of Exception
before handling the error normally. That's not nice.
4 comments:
Unknown said...
You should probably open a bug on the issue tracker for that, ideally with a patch (to fix the existing "bare" excepts), and maybe find out which PEP handles the stdlib style and suggest an amendment for it as well.
mackstann said...
Definitely agreed on filing a bug. This is low-hanging fruit that benefit everyone.
James Thiele said...
Sigh. I used a bare except yesterday. It's not a great idea in general but I wanted to provide more debugging info local to the exception than a stack trace would (easily) provide.
I'm kinda against blanket prohibitions.
Unknown said...
Sure, I'm against blanket prohibitions as well! But if I break a prohibition I require myself to clearly explain the reason in comments so it doesn't get mopped up as a mistake later.
New comments are not allowed.