4

I try to exit a script but it doesn't exit.

Here is my code:

import sys

try:
    ...
    print "I'm gonna die!"
    sys.exit()
except:
    ...

print 'Still alive!'

And the results are:

I'm gonna die!
Still alive!

WHY?

3 Answers 3

24

You are catching the SystemExit exception with your blanket except clause. Don't do that. Always specify what exceptions you are expecting to avoid exactly these things.

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

1 Comment

In this case except Exception would be enough as SystemExit doesn't inherit from that...
1

If you really need to exit immediately, and want to skip normal exit processing, then you can use os._exit(status). But, as others have said, it's generally much better to exit using the normal path, and just not catch the SystemExit exception. And while we're on the topic, KeyboardInterrupt is another exception that you may not want to catch. (Using except Exception will not catch either SystemExit or KeyboardInterrupt.)

1 Comment

Thank you! This is what I really need in this case.
1

sys.exit() is implemented by raising the SystemExit exception, so cleanup actions specified by finally, except clauses of try statements are honored, and it is possible to intercept the exit attempt at an outer level.

In your example SystemExit is catched by the following except statement.

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.