Why doesn't my variable value get passed to the finally block in python

China☆狼群 提交于 2020-01-25 04:30:11

问题


This is for python 2.7.10 Perhaps I'm not using the try..except..finally block correctly.

I need to check on the HTTP response code I get from a webpage. If I get a 200 code, everything is working. If I get any other code, report what code.

It works fine if I get a 200 HTTP code. If I get an exception, for some reason, it gives me an UnboundedLocalError, stating my variable isn't referenced. How do I get my variable to be recognized in the finally block?

Here's my code:

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)

This is the output we get if it works with a http 200 code:

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

This is the output we get if it gets an exception

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

Edit: If I wait like 5 min, and hit the website with a problem, then I get the response code / proper output. There might be a second question here as to why the website is taking so long to return the http 500 code (5 min to work).


回答1:


If an exception happens, then the assignment statement (resp = conn.getresponse().status) either never runs or never finishes.1 In that case, when the finally clause runs, you'll get an error because resp was never set to anything.

Based on the usage, it looks to me like you want to use else instead of finally. finally will run no matter what, but else will only run if the try suite finished without an exception.

1Consider an exception that happens in conn.getresponse -- Since an exception was raised, conn.getresponse never returns anything so there is no value to be bound to the resp on the left hand side.




回答2:


The solution is assign None to "resp" before "try" clause.Like this below.

resp = None
try:

When you run conn.request("GET", "/alive"), this may cause an Exception if timeout,then your code will enter "except" and then "finally" clause.But the variable haven't assigned,so it goes wrong.



来源:https://stackoverflow.com/questions/38258519/why-doesnt-my-variable-value-get-passed-to-the-finally-block-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!