exit 函数不工作,因为 except

exit function not working because of the except

当我尝试使用exit()函数时,代码没有因为异常而停止,如何取消?

def start(number):
    try:
        print(9 ** number)
        exit()
    except:
        print("problem")
        start()

您正在捕获所有异常,包括 SystemExit

使用 except Exception 以捕获所有内置的非退出异常。

在您的特定情况下,我建议只捕获 TypeError,因为这是您希望因 number 的错误类型而抛出的内容。也就是说,在您修复了 except-block 中对 start() 的无参数调用之后,这将引发 TypeError 本身。

您需要查看手册中的 Exception Hierarchy。基本异常被恰当地命名为 BaseException,并且所有其他异常都继承自它。 BaseException 有四个直接后代:SystemExitKeyboardInterruptGeneratorExitException

exit 引发了一个 SystemExit 异常,您正在使用无条件 except 子句捕获该异常。通常你只想捕获 Exception 及其任何后代,这些都是其他异常。所以:

try:
    ...
except Exception:
    ...

这允许其他三种异常按它们应该的方式冒泡,并允许您捕获更具体的异常树。最好你只捕获更具体的类型,尽可能具体。