Fwd: Should I use "if" or "try" (as a matter of speed)?

Mike Meyer mwm at mired.org
Wed Jul 13 04:01:40 CEST 2005

Dark Cowherd <darkcowherd at gmail.com> writes:

> But one advise that he gives which I think is of great value and is
> good practice is
> "Always catch any possible exception that might be thrown by a library
> I'm using on the same line as it is thrown and deal with it
> immediately."

Yuch. That sort of defeats the *purpose* of exceptions in Python:
letting you get on with the coding, and dealing with the errors when
it's convenient. Consider:

    out = file(datafile, "wb")
except IOError, msg:
    print >>sys.stderr, "Save failed:", msg
    if os.path.exists(datafile):

I don't even want to *think* writing the try/except clause for each
line. It reminds me to much of:

if (!(out = open(datafile, "w"))) {
   /* handle errors */
   return ;
if (write(out, genData1()) <0) {
   /* handle errors */
   return ;

Generally, I treat exceptions as exceptional. I catch the ones that
require something to be changed to restore the program or environment
to a sane state - and I catch them when it's convenient. The rest I
catch globally and log, so I can figure out what happened and do
something to prevent it from happening again.

Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.

More information about the Python-list mailing list