is there any overheard with try/except statements?

Paul McNett p at ulmcnett.com
Wed Mar 8 19:29:44 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?

The try structure is very efficient. However, when an exception happens 
at runtime, the creation of the exception object is expensive.

That said, it does seem to be considered Pythonic to "ask for 
forgiveness" instead of "asking for permission". If you check for every 
exceptional possibility before actually doing the thing you want to do, 
your code gets ugly very quickly.

I would use try...catch liberally, and then if profiling determines that 
you have a performance bottleneck (e.g., because an exception object is 
being created in lots of iterations of a loop) then factor out the try 
block in that case, placing a comment explaining why you did it that way.

-- 
Paul





More information about the Python-list mailing list