is there any overheard with try/except statements?

Roy Smith roy at panix.com
Wed Mar 8 19:28:54 EST 2006


In article <EfSdnS4P5s1475LZnZ2dnUVZ_vydnZ2d at rcn.net>,
 John Salerno <johnjsal at NOSPAMgmail.com> 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.

Repeat after me: "Python is not <fill in name of your favorite language>"

In C++ (and, I assume, C#), exception handling is relatively expensive, and 
is avoided for this reason.  It's also avoided (in C++, anyway) because 
it's only in the past few (5-10) years that you could pretty much count on 
whatever compiler you were using implementing them correctly.  Lastly, many 
C++/C# programmers came from C, where exceptions don't exist, so they're 
not used to using them.

But, that's not Python.  In Python, exceptions work as advertised, and 
they're cheap.  The pythonic way to do things is to embrace the maxim that 
"it's easier to ask forgivness than to ask permission".  It is usually 
cleaner and faster to write a try block than an if statement.  For example, 
I'll write:

try:
   x = foo[y]
except IndexError:
   blah

instead of

if y < len (foo):
   x = foo[y]
else:
   blah

every time.



More information about the Python-list mailing list