is there any overheard with try/except statements?

Alex Martelli aleaxit at yahoo.com
Thu Mar 9 01:53:31 EST 2006


John Salerno <johnjsal at NOSPAMgmail.com> wrote:

> 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?
> > 
> > Thanks.
> 
> Thanks guys! I had a feeling exceptions were nothing like in C languages
> (i.e. a pain to deal with).  :)

Right.  Anyway, Python makes it easy to MEASURE speed issues!  For
example, say that you wonder whether it's better to check a division by
0 in advance (you expect it to happen one in N times on average) or rely
on catching ZeroDivisionError -- one rare case where the two approaches
are just about equally easy to code, so you want to use the faster one.
Well, *MEASURE*...:

helen:~ alex$ python -mtimeit 'for x in range(33):
  if x==0: pass
  else: z=1.0/x
'
10000 loops, best of 3: 29.5 usec per loop

helen:~ alex$ python -mtimeit 'for x in range(33):
  try: z=1.0/x
  except ZeroDivisionError: pass
'
10000 loops, best of 3: 46.4 usec per loop

So, if a 0 happens about ` times in 33, Look Before You Leap (LBYL) is
faster than Easier to Ask Forgiveness than Permission (EAFP) in this
specific case -- and by using code that's close to your "real" one you
also learn how important to performance is to choose one or ther other.

In general, it's more frequent for EAFP to be handier and more solid,
and performance may well not matter -- but if you find yourself trying
to squeeze every last drop of performance from a region of your code
that profiling has shown to be a bottleneck, module timeit can help!


Alex



More information about the Python-list mailing list