Python尝试除了最后
看来我还不太掌握异常处理的窍门。我不知所措:( 以下代码有时会返回此错误:
File "applications/pingback/modules/plugin_h_pingback.py", line 190, in ping
db(table.id==id_).update(status=status)
UnboundLocalError: local variable 'status' referenced before assignment
我希望 status
始终已被分配一个值。难道是抛出了其他异常(可能是在内部的 try 中)并且finally 掩盖了它?
...
try:
server_url = self._get_pingback_server(target)
except PingbackClientError, e:
status = e.message
else:
try:
server = xmlrpclib.ServerProxy(server_url)
status = server.pingback.ping(self.source, target)
except xmlrpclib.Fault, e:
status = e
finally:
db(table.id==id_).update(status=status) # <-- UnboundLocalError
...
谢谢,HC
It looks like I don't quite have the hang of Exception handling yet. I'm at a loss :(
The following code sometimes returns this error:
File "applications/pingback/modules/plugin_h_pingback.py", line 190, in ping
db(table.id==id_).update(status=status)
UnboundLocalError: local variable 'status' referenced before assignment
I would expect status
to always have been assigned a value. Could it be that some other exception is thrown (perhaps in the inner try
) and the finally
obscures it?
...
try:
server_url = self._get_pingback_server(target)
except PingbackClientError, e:
status = e.message
else:
try:
server = xmlrpclib.ServerProxy(server_url)
status = server.pingback.ping(self.source, target)
except xmlrpclib.Fault, e:
status = e
finally:
db(table.id==id_).update(status=status) # <-- UnboundLocalError
...
Thanks, HC
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的代码并不总是为状态分配某些内容。我可以看到几种可能无法分配状态的方法,我在下面突出显示了它们:
我怀疑最有可能出现错误的位置是在内部 try 块中,您只能在其中捕获
xmlrpclib.Fault
而不是其他类型的异常。Your code doesn't always assign something to status. I can see a few ways that status might not be assigned and I've highlighted them below:
I suspect that the most likely place for the error is in the inner try block where you are only catching
xmlrpclib.Fault
and not other types of exceptions.作为一个简单的解决方案,我会在任何块之外初始化状态:
然后状态将始终被绑定。这不会解决任何未处理异常的问题,但会解决 UnboundLocalError。
(此外,在第一个块中,您使用 e.message 分配状态,在接下来的块中,您只需使用完整的错误 e,而不仅仅是消息。)
As a simple solution, I'd initialize status outside any blocks:
Then status will always be bound. That will not solve the problem of any unhandled exception, but it will solve the UnboundLocalError.
(Also, in the first block you assing status with e.message, in the following block, you just use the complete error e, not just the message.)