【问题标题】:Python3 missing exception when looping循环时Python3缺少异常
【发布时间】: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


【解决方案1】:

self._my_attribute[key] = value['property'] 中的潜在 KeyError 未被 except Exception 块覆盖。一旦它被引发,finally 块就会被执行(事实上,finally总是被执行,无论是否引发或什至处理了异常)。这可以通过使用分步调试器或在finally 块内使用简单的print('finally') 轻松验证。

这就是(以及其他原因)try 块应该尽可能少的原因。如果您知道该行可能会引发 KeyError 然后明确地 try-except 它:

for key, value in my_dict.items():
    print(key)
    try:
        self._my_attribute[key] = value['property']
    except KeyError as e:
        print('Key ', e, 'does not exist')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-05
    • 2016-02-09
    • 2010-10-17
    • 2020-01-05
    • 2021-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多