简体   繁体   中英

Exit script from inside of try-catch block in Python 3

I'm trying to exit a script from inside a try: except: block except it just goes on to the exception case.

None of these...

try:
    exit()
except:
    pass()

try:
    quit()
except:
    pass

import sys
try:
    sys.exit()
except:
    pass

...exit my script, they just go on to the except case.

How would I exit my script from inside one of these blocks?

All of these examples raise the SystemExit exception and you are catching that exception, a blank except clause will catch all exceptions.

This is the reason why you should always specify the exception you intend to catch or at least use except Exception eg

try:
    exit()
except Exception:
    pass

try:
    quit()
except Exception:
    pass

import sys
try:
    sys.exit()
except Exception:
    pass

With that change in place, all of you examples will cause your Python app to exit

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