python sys.exit not working in try

onlyvinish picture onlyvinish · Sep 18, 2014 · Viewed 38.2k times · Source
Python 2.7.5 (default, Feb 26 2014, 13:43:17)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> try:
...  sys.exit()
... except:
...  print "in except"
...
in except
>>> try:
...  sys.exit(0)
... except:
...  print "in except"
...
in except
>>> try:
...  sys.exit(1)
... except:
...  print "in except"
...
in except

Why am not able to trigger sys.exit() in try, any suggestions...!!!

The code posted here has all the version details.

I have tried all possible ways i know to trigger it, but i failed. It gets to 'except' block.

Thanks in advance..

Answer

tamasgal picture tamasgal · Sep 18, 2014

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