[英]My error handling code try/expect code giving me error "local variable referenced before assignment with try and except statement"
I added this code here meant for error handling我在这里添加了这段代码,用于错误处理
try:
music = session.query(Music).filter_by(Assetid=id).one()
music.firstname = new_AssetName
music.lastname = new_category
music.DOB = new_borrower
music.experience = new_status
music.experience = new_value
session.commit()
except Exception as e:
message = "Error updating player:" + e.toString()
finally:
return template('success.tpl', message=message)
and it keeps on giving me the error它不断给我错误
UnboundLocalError: local variable 'message' referenced before assignment
My solution was to make message a global variable so like:我的解决方案是让 message 成为一个全局变量,如下所示:
except Exception as e:
global message
message = "Error updating player:" + e.toString()
But this just gives me an error saying that message is not defined.但这只是给我一个错误,说消息未定义。 I am quite lost on how to fix this any help would be great我对如何解决这个问题很迷茫,任何帮助都会很棒
The message variable is not defined in your try block.消息变量未在您的try块中定义。 This means that when your code gets to the finally block, if the execution didn't raise an exception the message variable will be undefined and therefore raise the UnboundLocalError exception.这意味着当您的代码到达finally块时,如果执行没有引发异常,则消息变量将未定义,因此引发UnboundLocalError异常。
To solve this, you could simply do:要解决这个问题,您可以简单地执行以下操作:
try:
music = session.query(Music).filter_by(Assetid=id).one()
music.firstname = new_AssetName
music.lastname = new_category
music.DOB = new_borrower
music.experience = new_status
music.experience = new_value
session.commit()
message = "Successfully updated player"
except Exception as e:
message = f"Error updating player: {e}"
finally:
return template("success.tpl", message=message)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.