Skip to main content
 首页 » 编程设计

python之为什么我的变量值没有传递给 python 中的 finally block

2025年05月04日9zhenyulu

这是针对 python 2.7.10 也许我没有正确使用 try..except..finally block 。

我需要检查从网页获得的 HTTP 响应代码。 如果我收到 200 代码,则一切正常。如果我得到任何其他代码,请报告什么代码。

如果我得到一个 200 HTTP 代码,它工作正常。 如果我得到一个异常,出于某种原因,它会给我一个 UnboundedLocalError,说明我的变量没有被引用。如何让我的变量在 finally block 中被识别?

这是我的代码:

try: 
   conn = httplib.HTTPConnection(host, port=9000) 
   conn.request("GET", "/alive") 
   resp = conn.getresponse().status 
except Exception as e: 
   print "got some exception" 
   print "exception " + e  
   print "Exception msg: " + e.message 
   print "Args for exception: " + e.args 
finally: 
   if resp == 200: 
      print "got a 200 http response.  everything seems good" 
   if resp != 200: 
      print "didn't get a 200 http response.  something wrong" 
   print "this is the code we got: " + str(resp) 

如果使用 http 200 代码,这是我们得到的输出:

got a 200 http response.  everything seems good this is the code we got: 200 

如果出现异常,这是我们得到的输出

got some exception 
Traceback (most recent call last): 
  File "monitorAlive.py", line 27, in <module> 
    main() 
  File "monitorAlive.py", line 24, in main 
    get_status_code(host) 
  File "monitorAlive.py", line 16, in get_status_code 
    if resp == 200: 
UnboundLocalError: local variable 'resp' referenced before assignment 

编辑:如果我等了大约 5 分钟,访问网站时出现问题,那么我会得到响应代码/正确的输出。这里可能还有第二个问题,即为什么网站需要这么长时间才能返回 http 500 代码(5 分钟才能正常工作)。

请您参考如下方法:

如果发生异常,则赋值语句 (resp = conn.getresponse().status) 要么永远不会运行,要么永远不会完成。1 在这种情况下,当finally 子句运行时,您会得到一个错误,因为 resp 从未设置为任何内容。

根据用法,在我看来,看起来您想使用 else 而不是 finally。 finally 无论如何都会运行,但是 else 只会在 try 套件无异常完成时运行。

1考虑在 conn.getresponse 中发生的异常 -- 由于异常被引发,conn.getresponse 永远不会 < em>返回任何东西,因此没有值绑定(bind)到左侧的 resp。