【问题标题】:variable in try clause not accessible in finally clause - pythontry 子句中的变量在 finally 子句中无法访问 - python
【发布时间】:2014-01-23 18:59:57
【问题描述】:

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

当我在 mdb.connect() 调用中运行以下代码且没有错误时,代码运行良好。

但是当我故意插入错误时(例如,放入'localhostblahblah'),我在执行时收到'NameError: name 'con' is not defined'错误。

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

【问题讨论】:

  • 您希望发生什么?

标签: python mysql-python


【解决方案1】:

如果 mdb.connect 出错,则没有任何内容可分配给 con,因此不会被定义。

尝试使用else,而不是finally,它仅在没有异常时运行。 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()

【讨论】:

  • 我总是忘记你可以像在 Python 中那样使用else。我记得它也适用于whilefor 循环。
  • 他们只是喜欢将else 扔到所有东西中,不是吗?
  • 你会写成except mdb.Error as e吗?它的语法更清晰,适用于 Python 2.6+ 和 Python 3。
  • @KirkStrauser,是的,我个人会。没有检查不太相关的代码。更新
【解决方案2】:

去做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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-14
      • 1970-01-01
      • 2019-02-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多