variable in try clause not accessible in finally clause - python
Question: I am new to python, so sorry if this question is dumb, but can someone tell me
what's going on here.

When I run the following code with no errors in the mdb.connect() call, the
code runs fine.

But when I purposely insert an error (for example, put in
'localhostblahblah'), I get a 'NameError: name 'con' is not defined' error
when I execute.

I thought that variables defined in the try clause should be accessible in the
finally clause. What's going on?

    
    
    #!/usr/bin/python
    
    import MySQLdb as mdb
    import sys
    
    try:
        con = mdb.connect('localhost','jmtoung','','ptb_genetics')
    
    except mdb.Error, e:
        print "Error"
        sys.exit(1)
    
    finally:
        if con:
            con.close()
    


Answer: If `mdb.connect` errors, there's nothing to assign to `con`, so it doesn't get
defined.

Instead of `finally`, try using `else`, which is run only when there was no
exception. [Docs](http://docs.python.org/2/tutorial/errors.html#handling-
exceptions)

    
    
    try:
        con = mdb.connect('localhost','jmtoung','','ptb_genetics')
    
    except mdb.Error as e:
        print "Error"
        sys.exit(1)
    
    else:  # else instead of finally
        con.close()
    

