Program exited (sys.exit() called)
This exception is raised by the `sys.exit()` function. It is not considered an error but a clean way to terminate the Python interpreter.
- 1Calling `sys.exit()` to intentionally stop the program.
- 2The main script finishes execution, and Python's cleanup procedure raises it implicitly.
- 3Some high-level frameworks may use it to abort a process.
This exception is raised to terminate the program when `sys.exit()` is called.
import sys
try:
sys.exit("Exiting with a message")
except SystemExit as e:
print(f"Caught SystemExit: {e}")
expected output
Caught SystemExit: Exiting with a message
Fix 1
Use `try...finally` to ensure cleanup on exit
WHEN You need to perform a critical action (like saving a file or releasing a lock) before the script terminates.
import sys
try:
print("Doing work...")
sys.exit(0)
finally:
print("Cleaning up resources before exit.")
Why this works
A `finally` block is always executed before the function or `try` block is left, even when an exception like `SystemExit` is raised, making it perfect for cleanup.
Fix 2
Catch `SystemExit` only in specific top-level cases
WHEN A testing framework or application runner needs to prevent a script from actually terminating the whole process.
# In a test runner or interactive shell, not typical app code
try:
# Code that might call sys.exit()
run_user_script()
except SystemExit:
print("User script tried to exit.")
Why this works
By catching `SystemExit`, the parent process can intercept the termination request and continue its own execution. This is rarely done in standard applications.
import sys sys.exit(1) # raises SystemExit(1)
try:
run_script()
except SystemExit as e:
print(f"Script exited with code {e.code}")import atexit
@atexit.register
def cleanup():
save_state() # runs before exit even with sys.exit()✕ Catching `SystemExit` to prevent a program from closing
Calling `sys.exit()` is an intentional request to terminate. Blocking it usually goes against the programmer's intent and can leave the application in an unexpected state.
cpython/Python/sysmodule.c
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev