I am trying to catch a SystemExit
exception in the following fashion:
try:
raise SystemExit
except Exception as exception:
print "success"
But, it doesn't work.
It does work however when I change my code like that:
try:
raise SystemExit
except:
print "success"
As far as I am aware, except Exception as exception
should catch any exception. This is how it is described here as well. Why isn't that working for me here?
The SystemExit exception is inherited from this BaseException instead of Exception or StandardError as it is not any technical error so that it can be caught by the code that catches the exception. So when this exception is raised and if it cannot be handled then the Python interpreter exits.
SystemExit is an exception, which basically means that your progam had a behavior such that you want to stop it and raise an error. sys. exit is the function that you can call to exit from your program, possibily giving a return code to the system.
Wrap your main code in a try / except block, catch SystemExit , and call os. _exit() there, and only there! This way you may call sys. exit normally anywhere in the code, let it bubble out to the top level, gracefully closing all files and running all cleanups, and then calling os.
As documented, SystemExit does not inherit from Exception. You would have to use except BaseException
.
However, this is for a reason:
The exception inherits from BaseException instead of StandardError or Exception so that it is not accidentally caught by code that catches Exception.
It is unusual to want to handle "real" exceptions in the same way you want to handle SystemExit. You might be better off catching SystemExit explicitly with except SystemExit
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With