如果发生异常,如何确保 try/except 循环不执行所有内容?

How to make sure try/except loop doesn't execute everything if an exception occurs?

假设我有这个代码:

def my_func():
    print("Hello World")  # <-- This should work
    print(x)  # <-- This should NOT work, since x is undefined


try:
    my_func()
    # However, in my try-except loop, the function is being partially executed. 
    # I want it so that if there is an error, the function shouldn't execute at all, and nothing should happen
except Exception as e:
    print(e)

我想要的是执行函数,但如果发生错误,则根本不执行函数。我不知道 try/except 循环是否可行,因为这样做的目的是执行代码直到出现错误,但可能还有其他一些循环可以实现这一点。 抱歉,我知道这是一个非常初学者的问题,我可能应该知道这一点,但我是自学成才的,从来没有遇到过这个问题,也不知道该怎么做才能解决这个问题。谢谢!

如前所述,您想要的是不可能的。但是,您可以做的是以不同的方式构造代码,以便函数需要 x 才能 运行:

def my_func(x):
    print("Hello World")
    print(x)

my_func(x)  # Will raise an error if x is not provided

或者,您可以预先检查是否存在您需要的任何变量:

try:
    x
    # any other variable you need
    # this can also be done inside the function itself (probably better to do that tbh)
    my_func()

except NameError as e:
    print(e)

我知道未分配的变量可能不是您遇到的确切问题,但无论哪种方式,如果您不希望函数做一些重要的事情并且中途失败,运行 事先进行一些检查,即使只是在函数本身内部,以确保它有最好的完成机会。希望这对您有所帮助,如果不是您想要的,我们深表歉意。