即使在引发异常的情况下,继续在Python中的try子句中

时间:2019-01-25 11:01:56

标签: python try-catch

即使在引发异常的情况下,是否仍可以在try子句中继续执行代码?

这是代码示例。

outer_margin = 0.125  # Default Amazon
safe_zone = 0.25  # Default Amazon
safe_spine = 0.0625  # Default Amazon
if custom_measure is not None:
    if isinstance(custom_measure, dict):
        try:
            outer_margin = custom_measure["outer_margin"]
            safe_zone = custom_measure["safe_zone"]
            safe_spine = custom_measure["safe_spine"]
        except KeyError as e:
            logger.warning("Key {} not found, default value used.".format(e))

所有三个值都是可选的,因此键outer_margin可能不存在,但可能存在safe_zone。即使致电safe_zone引发异常,我也想联系outer_margin。有没有办法在单个try / except块中执行此操作?像这样:

# Not valid syntax
try:
    outer_margin = custom_measure["outer_margin"]
try:
    safe_zone = custom_measure["safe_zone"]
except KeyError as e:
    pass

在示例中,我已经找到了针对该情况的另一种解决方案,但是现在,我很想知道是否有一种方法可以继续执行try / except块,即使引发异常。

2 个答案:

答案 0 :(得分:0)

您可以使用dict.get而不是捕获KeyError异常。

if isinstance(custom_measure, dict):
    outer_margin = custom_measure.get("outer_margin")
    safe_zone = custom_measure.get("safe_zone")
    safe_spine = custom_measure.get("safe_spine")

如果"outer_margin"中不存在custom_measure,它将被设置为None

您还可以像这样None之外设置另一个默认值。

outer_margin = custom_measure.get("outer_margin", 0)

答案 1 :(得分:0)

如果您确实需要日志,请在此处重构try/except

def get_with_warning(data, key, default):
    if key in data:
        return data[key]
    else:
        logger.warning("Key {} not found, default value used.".format(key))
        return default

outer_margin = get_with_warning(custom_measure, "outer_margin", 0.125)
safe_zone = get_with_warning(custom_measure, "safe_zone", 0.25)
safe_spine = get_with_warning(custom_measure, "safe_spine", 0.0625)

如果没有,那么就这么简单:

outer_margin = custom_measure.get("outer_margin", 0.125)
safe_zone = custom_measure.get("safe_zone", 0.25)
safe_spine = custom_measure.get("safe_spine", 0.0625)