简体   繁体   中英

What is the proper way to exit the whole script?

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

fu()

So it should raise a recursion error after some time and when it does that I want to exit the whole code.

So what I am trying to get is:

hello
hello
...
last hello

But it gives something like:

hello
hello
...
last hello
last hello

So when it raises that error I want to do something and that's all, just quit, no more trying

I believe you should catch particular 'RecursionError' instead of all exceptions.

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

You need to add the base Exception type to the except and it will work.

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

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