Monday, January 24, 2005

Exception-based code antipatterns

To continue the topic of exception-based code, there are cases when bad code is easy to spot. For example, this snippet is almost always inappropriate:

# do something
except: # catch any possible exception
pass # and just ignore it
Semantically, this is equals to error-code-based code with no error checking. It has valid use cases but there are a few.

Another antipattern, more coupled specifically to Python:

# do something
except Exception, e:
# handle it
Most of the time you should catch specific exception class(es) instead of base Exception class. The problem with this approach is that in Python, everything is reported through exception mechanism, including syntax errors, keyboard interrupts, program exit, memory errors, etc. And usually you don't want to catch these kind of exceptional conditions.

This catch-all is often a sign of a sloppy programming, where a programmer was too lazy to list actual exception classes to catch or the calling code is known to raise all kind of exception and there is no documented exception class to look for (which is often the case for poorly written/abstracted modules).

Unfortunately, advise to catch specific exception classes has a drawback as well. When the calling code is updated it could raise new types of exception and thus handling code must be updated as well. For third-party code, this risk often could be mitigated by abstracting external interface and re-warping (and documentin) use of exception classes.


Blogger xamdam said...

Hi Max,
as for "drawback" in your last paragraph, shouldn't the
#do stuff
except Specific1, e:
except Specific1, e:
except Exception, e:
#all derived from exception
#all the rest
handle the potential updates in the called code?
Other Max.

12:46 AM  

Post a Comment

<< Home