Easy question on error catching

Erik Max Francis max at alcyone.com
Mon Apr 12 02:23:36 EDT 2004


Sean Berry wrote:

> So, how do I catch this error so that I can do something else with it?
> 
> Is it as simple as
> try:
>     x = int(t)
> except:
>     something else
> 
> or do I need to catch a ValueError specifically?

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.  This way only
what needs to get caught gets caught, and the rest gets passed up the
appropriate caller if necessary.

Granted, this is a special case since what you're trying to do is so
simple, but it's a good practice to follow in the future.

-- 
 __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
/  \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
\__/ Don't overestimate the decency of the human race.
    -- H.L. Mencken



More information about the Python-list mailing list