2014-01-23 25 views
2

我是python的新手,非常抱歉,如果這個問題是愚蠢的,但是有人能告訴我這裏發生了什麼。try子句中的變量不能在finally子句中訪問 - python

當我在mdb.connect()調用中沒有錯誤地運行以下代碼時,代碼運行良好。當我執行時,我故意插入一個錯誤(例如,放在'localhostblahblah'),我得到'NameError:name'con'未定義'錯誤。

我認爲在try子句中定義的變量應該可以在finally子句中訪問。這是怎麼回事?

#!/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() 
+0

你會期望發生什麼? – delnan

回答

8

如果mdb.connect錯誤,沒有什麼要分配給con,所以它不會定義。

而不是finally,請嘗試使用else,它僅在沒有異常時運行。 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() 
+0

我總是忘記你可以像Python那樣使用'else'。正如我記得的,它也適用於'while'和'for'循環。 – JAB

+0

他們只是喜歡把'else'扔進一切,不是嗎? – mhlester

+0

你會寫'除了mdb.Error as e'嗎?這是一個更清晰的語法,並在Python 2.6+和Python 3中工作。 –

1

做它EAFP風格:

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 
0

如果變量賦值的過程中發生錯誤,變量將不會被分配給。

>>> 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'