is there any overheard with try/except statements?

Steven D'Aprano steve at REMOVEMEcyber.com.au
Wed Mar 8 19:29:38 EST 2006


John Salerno wrote:

> One of the things I learned with C# is that it's always better to handle 
> any errors that might occur within the codes itself (i.e. using if 
> statements, etc. to catch potential out of range indexing) rather than 
> use too many try/catch statements, because there is some overhead every 
> time the program encounters the try.
> 
> Is this the case at all with Python, in terms of extra work or slower 
> speed? Or is try/except implemented differently in Python than it is in 
> other languages, so that it runs just like any other code?


Setting up the try... portion of the block is very 
lightweight. There is overhead, of course, but it is 
very little, and potentially less overhead that 
checking for the error condition. Dropping into the 
except... portion is not so lightweight.

The classic example of the "look before you leap" and 
"just do it" idioms involves looking up a key in a 
dictionary:

# method one
if some_dict.has_key(key):
     do_something_with(some_dict[key])
else:
     do_something_else()

# method two
try:
     do_something_with(some_dict[key])
except KeyError:
     do_something_else()


If you expect lots of missing keys, the first method 
will be quicker; if only a few, the second.



-- 
Steven.




More information about the Python-list mailing list