try blocks in Python vs. C++

David Abrahams david.abrahams at
Thu Sep 5 22:05:46 EDT 2002

"David LeBlanc" <whisper at> wrote in message
news:mailman.1031270709.27012.python-list at
> I think the biggest reason why try blocks aren't suggested for use in C++
> that they increase code size substantially (as do some other nice

That's not a very good generalization. C++ implementations vary
substantially on the over (and under-) heads implied by exception-handling

One reason you might want to avoid try blocks is that generally you want to
do cleanup unconditionally and rethrow the exception unmodified, and C++ has
no "finally" construct. Usually it works a lot better to use destructors of
local objects for this sort of thing, since you can re-use them and you
can't forget to "throw;" at the end.

BTW, saying "Stroustrup's C++ Book" isn't very specific (he has several),
and early editions of TC++PL contained some bad advice about C++ EH. See the
downloadable Appendix E at
for some good advice.

> Try...except is good practice in Python IMO.

Yeah, it's a completely different story in Python:

    Python has 'finally'

    __del__ methods don't execute as the stack is unwound
    (whereas C++ destructors do)

    throwing an exception to deal with ordinary conditions
    (e.g. StopIteration) is common, since unlike most C++
    implementations throwing an exception is no more
    expensive in Python than returning from a function.

           David Abrahams * Boost Consulting
dave at *

> > -----Original Message-----
> > From: python-list-admin at
> > [mailto:python-list-admin at]On Behalf Of Roy Smith
> > Sent: Thursday, September 05, 2002 16:54
> > To: python-list at
> > Subject: try blocks in Python vs. C++
> >
> >
> > I'm reading Stroustroup's C++ book, and came upon a piece of advice to
> > avoid using try blocks.  I use try blocks a lot in Python and gather
> > it's common practice among pythonistas.
> >
> > Is there something fundamentally different about try blocks in Python
> > and C++ which makes them more attractive to use in one vs. the other?
> > On the surface, they appear to be virtually identical in just about
> > every respect.  Is it simply a cultural difference?  Or just the
> > author's own personal style?
> > --
> >

More information about the Python-list mailing list