简体   繁体   English

如何跳出 python 中的 try 循环?

[英]How do I break out of a try loop in python?

Please refer to the following code:请参考以下代码:

import sys
def x():
    try:
        y()
    except:
        print("exception caught")
def y():
    sys.exit()
x()

In this instance, the try loop in function x() will be carried over to the function y() , causing the except loop to run due to sys.exit() raising an error.在这种情况下,函数x()的 try 循环将被传递到函数y() ,导致由于sys.exit()引发错误而导致 except 循环运行。 I know, we can change it to raise SystemExit to exit it, but is there a way to break out of the try loop or is there a better way of writing this code?我知道,我们可以更改它以提高 SystemExit 以退出它,但是有没有办法跳出 try 循环,或者有没有更好的方法来编写此代码?

Thank you for reading and thanks in advance.感谢您阅读并提前致谢。

您可以编写except Exception ,它会捕获代码中所有常见的except Exception ,但不会捕获SystemExit异常,因为它不是从Exception继承的,而是从BaseException继承的

In general, it is a bad idea to simply use except without catching any errors... So my advice is to go for the other way you mention, like this:一般来说,简单地使用除非没有发现任何错误是一个坏主意......所以我的建议是采用你提到的另一种方式,如下所示:

import sys
def x():
    try:
        y()
    except SystemExit:
        print("exception caught")
def y():
    sys.exit()
x()

I think you want to exit from try block without getting caught by except block, for this just我认为你想退出 try 块而不被 except 块抓住,因为这只是

except Exception as e:

instead of代替

except:

Here is the full code:这是完整的代码:

import sys
def x():
    try:
        y()
    except as e:
        if e is SystemExit:
            print("exception caught")
def y():
    raise SystemExit
x()

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

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