Is python exception handling more efficient than PHP and/or other languages? Is python exception handling more efficient than PHP and/or other languages? python python

Is python exception handling more efficient than PHP and/or other languages?


Historically, in languages like C++, exceptions have been very slow compared to other forms of flow control in the same language.

In C++, there are two things at work:

  • Throwing an exception is very complex. The stack needs to be unwound, and doing so in native code is much harder than in a high-level VM-based language.
  • Regular, direct flow control is extremely fast. It's native code; a branch is a couple instructions, where an exception rolling back the stack invokes a complex algorithm (looking up stack data in a large, possibly compressed table, and so on).

This disparity in performance led to the general wisdom behind exceptions: only do it for unusual things, so it's only used where it's most beneficial and not where it'll hurt performance.

This does not apply to high-level languages. This is also for two reasons:

  • Rolling back the stack is much, much simpler. The stack is very easy to examine; you don't need magic tables to know how far to roll back the stack and what objects are constructed at any given time.
  • Regular program flow is inherently slower. In a VM-based language, everything simply takes more work to begin with.

Exceptions still aren't free, but the disparity is no longer something to worry so much about. This means the general wisdom formed in C++ is misapplied here. Exceptions are regularly used in normal program flow.

In fact, they're built into language, in constructs you use all the time. Every time you use an iterator--every for x in xrange(1000), a StopIteration exception is used to end the loop.

Choose exceptions or linear flow control in Python based on which makes more sense. Don't choose based on performance, unless you're actually in an inner loop where performance matters; in that case, as always, profile and find out if it actually matters.

(I can't speak for PHP.)


I don't believe that the EAFP encourages the use of exceptions for flow control. Rather, it tells us that we needn't bother checking for the existence of a particular key in a dictionary or property of an object before we reference it.

Throwing exceptions as an alternative to if statements or having correct while statements or instead of using break or continue inside of a loop does not fall under that category. That's lazy, error-prone progamming and it should be avoided.


the great Alex Martelli gives a good overview of EAFP vs. LBYL in the book 'Python In A Nutshell'. (He heavily leans towards using EAFP)

def worth reading:
http://books.google.com/books?id=JnR9hQA3SncC&lpg=PA134&ots=JaaWGy-24u&dq=alex%20martelli%20eafp%20lbyl&pg=PA134#v=onepage&q&f=false