突破try-except块

时间:2020-10-19 09:47:02

标签: python

我有一个嵌套的try-except-finally块,在该块中,我连续运行几个函数(假设以前的函数起作用)。我有一个条件,需要在开始时检查(本质上是检查该功能是否已在当天运行),并且如果此语句为false,我想直接跳到最后。

我可以通过简单地强制发生错误来做到这一点(即写x = 1/0,但似乎应该有更好的方法来做到这一点)。

我的代码如下:

error = False
conditions = False

try:
    # Do stuff here
    if not condition:
        # Here I want to go directly to finally
except Exception:
    error = True
else:
    try:
        # Do stuff here
    except Exception:
        error = True
    else:
        try:
            # Do stuff here
        except Exception:
            error = True
finally:
    if error:
        # Report that an error occurred
    else:
        # Report that everything went well

1 个答案:

答案 0 :(得分:1)

怎么样?

要在此答案的注释中使用宫城先生的出色措辞,它会颠倒逻辑,以便仅在满足条件时继续进行。

error = False
conditions = False

try:
    # Do stuff here
except Exception:
    error = True
else:
    if condition:  # The inverted condition moved here.
        try:
            # Do stuff here
        except Exception:
            error = True
        else:
            try:
                # Do stuff here
            except Exception:
                error = True
finally:
    if error:
        # Report that an error occurred
    else:
        # Report that everything went well