I have it drilled into my head that (at least in PHP) it is badbadmojo to use try... catch blocks for flow control. What I’ve learned is to use them only to handle unexpected errors, not determine the logic flow of the program, because catch blocks are expensive.
Now that I’m learning python, I see a lot of exceptions everywhere and the EAFP principle. Does this mean that python is more efficient at handling exceptions, so I don’t need to be as worried about them for flow control, or does the principle still stand? If not, is PHP the exception from the norm (as compared to other languages), or is Python?
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:
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:
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), aStopIterationexception 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.)