首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >中断try-except块

中断try-except块
EN

Stack Overflow用户
提问于 2020-10-19 17:47:02
回答 1查看 54关注 0票数 0

我有一个嵌套的try-except finally块,我在其中连续运行几个函数(假设前面的函数可以工作)。我有一个条件,我在开始时检查(本质上是检查函数是否已经在当天运行),如果这条语句是假的,我想直接跳到最后。

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

我的代码如下所示:

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-10-19 17:58:54

这个怎么样?

为了在对这个答案的评论中使用MisterMiyagi的出色措辞,它颠倒了逻辑,只有在满足条件时才继续。

代码语言:javascript
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64424894

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档