python sys.exit not working in try [duplicate]

眉间皱痕 提交于 2019-11-29 03:27:33

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

based on python wiki :

Since exit() ultimately “only” raises an exception, it will only exit the process when called from the main thread, and the exception is not intercepted.

And:

The exit function is not called when the program is killed by a signal, when a Python fatal internal error is detected, or when os._exit() is called.

Therefore, If you use sys.exit() within a try block python after raising the SystemExit exception python refuses of completing the exits's functionality and executes the exception block.

Now, from a programming perspective you basically don't need to put something that you know definitely raises an exception in a try block. Instead you can either raise a SystemExit exception manually or as a more Pythonic approach if you don't want to loose the respective functionalities of sys.exit() like passing optional argument to its constructor you can call sys.exit() in a finally, else or even except block.

Method 1 (not recommended)

try:
    # do stuff
except some_particular_exception:
    # handle this exception and then if you want 
    # do raise SystemExit
else:
    # do stuff and/or do raise SystemExit
finally:
    # do stuff and/or do raise SystemExit

Method 2 (Recommended):

try:
    # do stuff
except some_particular_exception:
    # handle this exception and then if you want 
    # do sys.exit(stat_code)
else:
    # do stuff and/or do sys.exit(stat_code)
finally:
    # do stuff and/or do sys.exit(stat_code)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!