简体   繁体   English

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

[英]Continue in a try clause in Python, even if the exception is raised

Is there any way to continue code execution in a try clause, even when the exception is raised? 是否有任何方法可以在try子句中继续执行代码,即使引发异常也是如此?

This is the code example. 这是代码示例。

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))

All three values are optional, so the key outer_margin may not exist, but safe_zone may be present. 这三个值都是可选的,因此键outer_margin可能不存在,但是safe_zone可能存在。 I would like to reach safe_zone even if calling outer_margin raises an exception. 我想到达safe_zone即使调用outer_margin引发异常。 Is there any way to do this in a single try/except block? 有没有办法在单个try / except块中执行此操作? Something like: 就像是:

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

I already found a different solution to the case in the example, but now I am curious to know if there is a way to continue down one try/except block, even if the exception is raised. 我已经在示例中找到了针对该情况的另一种解决方案,但是现在我很想知道是否有一种方法可以继续执行一个try / except块,即使引发异常也是如此。

You can use dict.get instead of catching the KeyError exception. 您可以使用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")

if "outer_margin" does not exist in custom_measure it will be set to None . 如果"outer_margin"不存在custom_measure它将被设置为None

You can also set another default value than None like this. 您也可以像这样设置除None以外的其他默认值。

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

If you really need the log, refactor the try/except out of there: 如果您确实需要日志,请从那里重构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)

If not, then it's as easy as this: 如果没有,那么就这么简单:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM