How "expensive" are Exceptions?

Jason Orendorff jason at jorendorff.com
Sun Mar 10 21:27:09 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?

Hi.  You already got one good answer on this, but another
tack is:  *Everything* in Python is *much* slower than
the corresponding thing in C++, except

  * hashtables
  * strings
  * programming  ;)

...so why worry?  What's "very expensive" in C++ is not
something you'd worry about in Python.


Yet another tack is this:  If you look closely at Python's
implementation, you'll notice that you're actually paying
the cost of exception handling *even when no exception is
thrown*.  So you might as well use the exception-handling
features of the language whenever it seems natural to do so.

To understand this, consider that Python is written in C,
which doesn't have exceptions.  How do you handle errors in
C?  You check the return value of every function call.  This
is what Python does, and it's how Python implements
exceptions, too.  This is the major cost of exception-handling
in Python:  checking every return value.  (Good C++ compilers
cleverly avoid this cost; Python doesn't, alas.)  Obviously
this must be done whether an exception was thrown or not;
that's the whole point.

## Jason Orendorff    http://www.jorendorff.com/





More information about the Python-list mailing list