adding a simulation mode

Steven D'Aprano steve+comp.lang.python at
Fri Jul 13 04:37:42 CEST 2012

On Thu, 12 Jul 2012 14:20:18 +0100, andrea crotti wrote:

> One thing that I don't quite understand is why some calls even if I
> catch the exception still makes the whole program quit.

Without seeing your whole program, we can't possibly answer this. But by 
consulting my crystal ball, I bet you have something like this:

    do_stuff()  # run your program
except Exception as e:
    # pointlessly catch exceptions I can't handle, which has the
    # bonus of making debugging MUCH MUCH harder
# end of file, nothing further to do

When do_stuff() fails, "here" gets printed, and then the program exits 
because there's nothing else to do.

Catching exceptions doesn't magically cause the code to continue from the 
point of the error. It doesn't work like that. Execution skips from where 
the error occurred to the except clause. Once the except clause has run, 
anything following the except clause runs, and then the program ends as 

If you haven't already done so, I recommend you go through the tutorial:

in particular the part about exception handling:

> For example this
>     try:
>         copytree('sjkdf', 'dsflkj')
>         Popen(['notfouhd'], shell=True)
>     except Exception as e:
>         print("here")

What is "Popen" and where is it from?

My first guess was os.popen, but that doesn't take a shell argument:

py> os.popen(['ls', '-l'], shell=True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: popen() got an unexpected keyword argument 'shell'

> behaves differently from:
>     try:
>         Popen(['notfouhd'], shell=True)
>         copytree('sjkdf', 'dsflkj')
>     except Exception as e:
>         print("here")
> because if copytree fails it quits anyway. 

Well of course it does. If copytree fails, the try block ends and 
execution skips straight to the except block, which runs, and then the 
program halts because there's nothing else to be done.

That at least is my guess, based on the described symptoms.


More information about the Python-list mailing list