python sys.exit not working in try [duplicate]

sys.exit() raises an exception, namely SystemExit. That’s why you land in the except-block.

See this example:

import sys

try:
    sys.exit()
except:
    print(sys.exc_info()[0])

This gives you:

<type 'exceptions.SystemExit'>

Although I can’t imagine that one has any practical reason to do so, you can use this construct:

import sys

try:
    sys.exit() # this always raises SystemExit
except SystemExit:
    print("sys.exit() worked as expected")
except:
    print("Something went horribly wrong") # some other exception got raised

Leave a Comment