try子句中的变量在finally子句python中不可访问

2024-10-03 15:21:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,如果这个问题很愚蠢,很抱歉,但是有人能告诉我这里发生了什么事吗。在

当我在mdb.连接()调用,代码运行正常。在

但当我故意插入一个错误(例如,put in'localhostblahblah')时,我得到一个'NameError:name'con'is not defined'error when I execute'。在

我认为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()

Tags: inimportput错误syserrorcontry
3条回答

如果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()

如果变量赋值过程中发生错误,变量将不会被赋值给。在

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

执行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

相关问题 更多 >