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

Mike Meyer mwm at mired.org
Tue Jul 12 22:01:40 EDT 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:

try:
    out = file(datafile, "wb")
    out.write(genData1())
    out.write(genData2())
    out.write(genData3())
except IOError, msg:
    print >>sys.stderr, "Save failed:", msg
    if os.path.exists(datafile):
       os.unlink(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 ;
}
etc.

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