1

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?

0

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.