Python SystemExit Exception
Example
Stop the program with sys.exit():
import sys
print("Before sys.exit()")
sys.exit()
print("After sys.exit()")
Try it Yourself »
Definition and Usage
The SystemExit exception is raised by sys.exit() to stop the program.
It is not an error. If it is not caught, the program ends without a traceback (error message). In the example, the last line never runs.
SystemExit does not inherit from Exception, so except Exception does not catch it.
Exception Handling
Example
Catch the SystemExit in a try...except statement:
import sys
try:
sys.exit()
except SystemExit:
print("sys.exit() was called")
Try it Yourself »
Related Pages
Read more about handling errors in our Python Try Except Tutorial.