【发布时间】:2019-12-28 03:27:27
【问题描述】:
我必须在类中定义一个属性,我想以最 Pythonic 的方式管理错误。
这是我迄今为止尝试过的代码。我不知道为什么我不能在下面的代码中“到达”异常。
# global variable to be used in the example
my_dict = {"key1": {"property": 10}, "key2": {}}
class Test(object):
@property
def my_attribute(self):
try:
return self._my_attribute
except AttributeError:
self._my_attribute = {}
for key, value in my_dict.items():
print(key)
self._my_attribute[key] = value['property']
except Exception:
print('error')
# I would like to manage my error here with a log or something
print("I am not reaching here")
finally:
return self._my_attribute
if __name__ == '__main__':
Test().my_attribute
我希望在 for 循环的第二次迭代中遇到异常情况,因为它是 KeyError(“key2”没有“属性”)。但它只是擦肩而过。在此示例中,如果脚本运行,它不会打印“我没有到达这里”。谁能解释为什么我看到这个错误?谢谢!
【问题讨论】:
-
“但它没有” 那它做了什么?
-
希望此更改是一个可重现的示例。我也编辑了这个问题。回答第二条评论:我认为它会进入 Exception 子句,但它“忽略”了它。
标签: python-3.x exception error-handling