Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

variable in try clause not accessible in finally clause - python

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()
like image 619
jmtoung Avatar asked Dec 20 '22 19:12

jmtoung


1 Answers

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

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()
like image 188
mhlester Avatar answered Jan 06 '23 08:01

mhlester