简体   繁体   English

跳出 try-except 块

[英]Breaking out of a try-except block

I have a nested try-except-finally block where I run several functions in succession (assuming the previous ones worked).我有一个嵌套的 try-except-finally 块,我在其中连续运行多个函数(假设前面的函数有效)。 I have a condition that I check at the start (which essentially checks if the function has already been run that day) and if this statement is false, I want to jump straight to the finally.我有一个条件,我在开始时检查(它基本上检查该函数是否已经在当天运行),如果此语句为假,我想直接跳到 finally。

I can do this by simply forcing an error to occur (ie writing x=1/0 but it seems there should be a better way to do this).我可以通过简单地强制发生错误来做到这一点(即写 x=1/0 但似乎应该有更好的方法来做到这一点)。

My code looks like this:我的代码如下所示:

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

How about this?这个怎么样?

To use MisterMiyagi's excellent wording in the comments to this answer, it inverts the logic to proceed only when the condition is met.要在此答案的评论中使用 MisterMiyagi 的出色措辞,它会反转逻辑以仅在满足条件时继续。

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

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

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