try子句中的变量在finally子句-python中不可访问
我是python新手,如果这个问题很愚蠢,那么很抱歉,有人能告诉我这里发生了什么吗 当我在mdb.connect()调用中没有错误地运行以下代码时,代码运行良好 但当我故意插入错误(例如,放入'localhostblahblah')时,我会得到一个'NameError:name'con'is not defined'错误 我认为try子句中定义的变量应该可以在finally子句中访问。发生什么事了try子句中的变量在finally子句-python中不可访问,python,mysql-python,Python,Mysql Python,我是python新手,如果这个问题很愚蠢,那么很抱歉,有人能告诉我这里发生了什么吗 当我在mdb.connect()调用中没有错误地运行以下代码时,代码运行良好 但当我故意插入错误(例如,放入'localhostblahblah')时,我会得到一个'NameError:name'con'is not defined'错误 我认为try子句中定义的变量应该可以在finally子句中访问。发生什么事了 #!/usr/bin/python import MySQLdb as mdb import s
#!/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()
如果
mdb.connect
出错,则没有任何内容可分配给con
,因此无法对其进行定义
尝试使用else
,而不是finally
,它仅在没有异常时运行
Do it风格:
如果变量分配过程中发生错误,则不会将变量分配给
>>> 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'
>x=3
>>>尝试:
... x=打开(r'C:\xxxxxxxxxxxxx')
... 最后:
... 打印(x)
...
3.
回溯(最近一次呼叫最后一次):
文件“”,第2行,在
IOError:[Errno 2]没有这样的文件或目录:“C:\\XXXXXXXXXXXXX”
您希望发生什么?我总是忘记您可以在Python中像那样使用else
。正如我所记得的,它在和循环中也起作用。它们只是喜欢把或者扔进任何东西中,不是吗?除了mdb,你会把它写成吗。错误是e
?这是一个更清晰的语法,在Python2.6+和Python3中都可以使用。@KirkStrauser,是的,我个人愿意。没有检查不太相关的代码。更新
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
>>> 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'