Fwd: Should I use "if" or "try" (as a matter of speed)?
Christopher Subich
spam.csubich+block at block.subich.spam.com
Tue Jul 12 15:43:46 EDT 2005
Dark Cowherd wrote:
> 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."
That's fine advice, except for when it's not. Consider the following code:
try:
f = file('file_here')
do_setup_code
do_stuff_with(f)
except IOError: # File doesn't exist
error_handle
To me, this code seems very logical and straightfoward, yet it doesn't
catch the exception on the very next line following its generation. It
relies on the behavior of the rest of the try-block being skipped -- the
"implicit goto" that Joel seems to loathe. If we had to catch it on the
same line, the only alternative that comes to mind is:
try: f=file('file_here')
except IOError: #File doesn't exist
error_handle
error_flag = 1
if not error_flag:
do_setup_code
do_stuff_with(f)
which nests on weird, arbitrary error flags, and doesn't seem like good
programming to me.
More information about the Python-list
mailing list