退出整个脚本的正确方式是什么?

2024-04-25 09:38:23 发布

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

def fu():
    try:
        print('hello')
        fu()
    except:
        print('last hello')
        exit()

fu()

因此,它应该在一段时间后引发一个递归错误,当它这样做时,我希望退出整个代码

所以我想得到的是:

hello
hello
...
last hello

但它给出了如下信息:

hello
hello
...
last hello
last hello

所以当它出现错误时,我想做点什么,就这样,退出,不再尝试


Tags: 代码信息hellodef错误exitlastprint
2条回答

您需要将基本异常类型添加到except,它将正常工作

def fu():
    try:
        print('hello')
        fu()
    except Exception:
        print('last hello')
        exit()
fu()

我认为您应该捕获特定的“递归错误”,而不是所有异常

def fu():
    try:
        print('hello')
        fu()
    except RecursionError as re:
        print('last hello')
        exit()
fu()

相关问题 更多 >