[python] using try: finally: except

Carl Banks imbosol at aerojockey.invalid
Thu Jun 17 17:47:44 EDT 2004


David Stockwell wrote:
> So I surmise one way to guarantee this does what I need would be to do this:
> 
> try:
>    x = 'hello'
> except Exception, e:
>    print "oops"
> 
> y = 'world'
> print x," ", y
> 
> Wouldn't that guarantee y and the print gets executed no matter what? My 
> exception catches miscellaneous errors and then processing continues....  I 
> suspect that wouldn't hold for a complex case where the action in the try 
> block causes a fatal error of some sort....

Not really.  It's not very likely (but not impossible) for the except
block you have here to throw an exception.  But in more realistic
situations, an exception might happen in the except block, and then
your y='world' statement will not be executed.

To show you that even print "oops" can throw an exception, try
executing the following code:

    try:
        import sys
        sys.stdout = None
        x = 'hello'
        1/0
    except:
        print "oops"
    y = 'world'
    print x," ",y

It should print a traceback, but not "hello world".

The right way is:

    try:
        try:
            x = 'hello'
        except:
            print "oops"
    finally:
        y = 'world'
        print x," ",y


-- 
CARL BANKS                      http://www.aerojockey.com/software
"If you believe in yourself, drink your school, stay on drugs, and
don't do milk, you can get work." 
          -- Parody of Mr. T from a Robert Smigel Cartoon



More information about the Python-list mailing list