使用异常作为goto是一种pythonic方法吗?

2024-04-26 03:24:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一组复杂的条件,一旦满足了,我就想退出。你知道吗

为此,我希望在它们周围使用try: / except:结构,以便在适当的时间退出,这类似于goto。一个复杂的例子(使用raisebreakwhile)是:

class Minor(Exception):
    pass
class Major(Exception):
    pass

age = 15
while True:
    try:
        if age > 18:
            raise Major
        else:
            raise Minor
    except Major:
        print('major')
        break
    except Minor:
        print('minor')
        break

这种例外的使用是不是有点像Python?换言之:异常的目的是只捕获本来是回溯的东西,还是它们有像上面那样的一般用途?你知道吗

编辑:在下面的评论中,我想澄清的是,我并不是在研究如何简化这段特定的代码——真正的代码在嵌套循环和条件下要复杂得多。我感兴趣的部分是,是否有理由特别反对使用例外。


Tags: 代码ageexceptionpass条件结构classraise
1条回答
网友
1楼 · 发布于 2024-04-26 03:24:12

不,这不是Python式的方法。通常用于立即从嵌套循环转义的流控制方法是将逻辑放入函数中并使用return语句。你知道吗

PEP 3136曾被提议作为一种使用带标签的break和continue语句从嵌套循环中转义的方法:

Labeled break and continue can improve the readability and flexibility of complex code which uses nested loops.

python3.1拒绝了这个PEP。圭多wrote

I'm rejecting it on the basis that code so complicated to require this feature is very rare. In most cases there are existing work-arounds that produce clean code, for example using 'return'.

相关问题 更多 >