devork

E pur si muove

Should bare except statements be allowed in the Python stdlib?

Thursday, August 13, 2009

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.

Thursday, August 13, 2009 | Labels: |

4 comments:

James 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.

Floris Bruynooghe 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.

Subscribe to: Post Comments (Atom)