6

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()
1
  • What would you expect to happen? Commented Jan 23, 2014 at 19:02

3 Answers 3

10

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()
Sign up to request clarification or add additional context in comments.

4 Comments

I always forget that you can use else like that in Python. It also works on while and for loops, as I remember.
They just love throwing else into everything, don't they?
Would you write that as except mdb.Error as e? It's a much clearer syntax and works in both Python 2.6+ and Python 3.
@KirkStrauser, yes I personally would. hadn't inspected the less pertinent code. updated
1

Do it EAFP style:

try: con = mdb.connect('localhost','jmtoung','','ptb_genetics')
except mdb.Error, e: #handle it
finally:
    try: con.close()
    except NameError: pass # it failed to connect
    except: raise # otherwise, raise that exception because it failed to close

Comments

0

If an error occurs in the process of variable assignment, the variable will not be assigned to.

>>> x = 3
>>> try:
...     x = open(r'C:\xxxxxxxxxxxxxxx')
... finally:
...     print(x)
...     
3
Traceback (most recent call last):
  File "<interactive input>", line 2, in <module>
IOError: [Errno 2] No such file or directory: 'C:\\xxxxxxxxxxxxxxx'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.