简体   繁体   中英

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. 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?

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

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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