try blocks in Python vs. C++

Sean 'Shaleh' Perry shalehperry at attbi.com
Thu Sep 5 20:11:42 EDT 2002


On Thursday 05 September 2002 16:53, Roy Smith wrote:
> 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?

If I recall, Stroustrup's advice is to let higher level code deal with errors 
and not to avoid try's entirely.  The python equivalent would be:

def func():
    ...
    ...
    i_may_except
    ...
    ...

try:
    func()
except ....:
    ...

if you write code like:

def func():
    try:
      do this
    except ...:
      ...

    try:
      do that
    except ...:
      ...

it is no better than the old style of testing each and every function call's 
return value.  You spend more time reading and writing error handling code 
than anything else.




More information about the Python-list mailing list