[Tutor] Try except really better than if?

Alan Gauld alan.gauld at btinternet.com
Mon Jan 10 03:10:22 CET 2011

"Karim" <karim.liateni at free.fr> wrote

> I am using more and more try except statement. But I discussed with 
> a very experienced C++ programmer.
> And he told me that at least in C++ using too many try -catch 
> statements are making the code slower.

That's true, but Bjarne Stroustrup put them in for a reason - and they
are still the "official" error handling mechanism in C++.  And Java
and Object Pascal borrowed them from C++ (which actually borrowed
them from ADA) - so there must be something good about them!
They are good practice in Python for the same reasons they are
good practice in ADA, C++, Java etc....

However, using exceptions like if/else blocks is bad practice.
You need to use them like a commit in SQL - to protect a whole
block of code. Putting try/except around every line of code
defeats the purpose, wrap atomic blocks of code not the
individual lines.

   something else
   the last
except Error1: # do something
except Error2: # do something
except Error3: # do something
 finally: # tidy up

is better to maintain than

try: something
except Error1: # do something
try: something else
except Error2: # do something
try: another
except Error1: # and again
try: the last
except Error3: do it
tidy up

In addition to the excellent caveats posted by Steven and Modulok, I'd
also add the reminder that code has about 20% of its cost in initial
development and the other 80% in "maintenance" (bug fixing and
enhancement) so readability and flexibility really count.

Finally, C++ virtual functions are slower than static functions, but 
doesn't mean you should write switch statements rather than use
polymorphism... Premature optimisation again - speed isn't
everything... fast enough is good enough.


Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list