Python:try/except块后Exception变量消失引发未定义错误
问题原因与解决方案
错误原因
你遇到的local variable 'exception' referenced before assignment错误,是Python的except Exception as <变量名>语法特性导致的:当except代码块执行完毕后,Python会自动删除as后面绑定的变量,目的是切断变量对异常对象的引用,让垃圾回收机制可以及时清理这些对象。
你的代码中,虽然一开始给exception赋值了None,但每次进入except块时,exception会被重新绑定到当前的异常对象;而当except块执行完pass后,这个变量就会被Python删除。当所有日期格式解析都失败后,循环结束时exception变量已经不存在了,所以执行raise exception时就会触发“变量未定义”的错误。
修复方案
换一个独立变量来保存最后一次的异常,避免使用except as后面的变量直接保存:
import datetime last_exception = None updated_at = None test_str = "obviously wrong" for datetime_format in ['%d-%b-%Y %H:%M', '%Y-%m-%d %H:%M']: try: updated_at = int(datetime.strptime(test_str, datetime_format).timestamp()) break except Exception as e: last_exception = e if updated_at is None: raise last_exception
这样每次异常都会被赋值给last_exception,这个变量不会被except块自动清除,循环结束后可以正常抛出最后一次的异常。
内容的提问来源于stack exchange,提问作者Grzegorz Z.
相关产品推荐
相关产品推荐

