How "expensive" are Exceptions?

Peter Hansen peter at engcorp.com
Sun Mar 10 20:01:06 EST 2002


Michael 'Mickey' Lauer wrote:
> 
> Hi, given the fact that excpetion handling can be very
> expensive in languages like C++ - is python similar in
> this aspect?
[...]
> Which version would be to prefer if the return types
> are distributed evenly?
> 
> try:
>     a, b = somefunc()
> except:
>     return None
> ...

Never do this. :-)  You have not specific which exception you
are catching, so you'll quietly hide all exceptions including
things like out of memory problems and so forth.

In this case, a quick check at the interactive prompt reveals
you should be looking for TypeError.

> selection = somefunc()
> if len( selection ) != 2:
>     return None
> else:
>     model, iter = selection
> ...

Definitely less readable, isn't it?  Given this sort of difference,
you should probably be much less concerned with raw performance
and more with readability and maintainability.  Only optimize
when you have actually hit a performance bottleneck.

A search at Google <hint> with the search pattern 
"python exception handling performance" reveals the answer to your
original question, no more than four hits down:

 http://aspn.activestate.com/ASPN/Mail/Message/python-list/998253

Short answer: exceptions are not expensive.

-Peter



More information about the Python-list mailing list