Easy question on error catching
Andrew Dalke
adalke at mindspring.com
Mon Apr 12 16:45:31 EDT 2004
Erik Max Francis:
> What you wrote will work, but catching a ValueError (except ValueError:
> ...) is a better solution. Especially in dynamically typed languages
> like Python, it's a good idea to catch the most restrictive error you
> think you need, and then expand the net if it's required.
To elaborate, suppose you press control-C inside of the try
block. That the signal for Python to stop what it's doing. Python
converts that into an exception. If nothing catches it then
the top-level reports the normal exception and traceback.
If you have a bare "except:" then in addition to telling Python
to ignore the ValueError when the string doesn't contain an
integer, you're also telling Python to ignore control-C, out-of-
memory exceptions and a few others.
I've actually had something like this happen to me
try:
v = flaot(s)
except:
v = 0.0
See the misspelling? It raised a NameError which was caught
by the bare except: so for every case I was setting v to 0.0.
Andrew
dalke at dalkescientific.com
More information about the Python-list
mailing list