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()
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With