SystemExit
PythonINFONotableControl FlowHIGH confidence

Program exited (sys.exit() called)

What this means

This exception is raised by the `sys.exit()` function. It is not considered an error but a clean way to terminate the Python interpreter.

Why it happens
  1. 1Calling `sys.exit()` to intentionally stop the program.
  2. 2The main script finishes execution, and Python's cleanup procedure raises it implicitly.
  3. 3Some high-level frameworks may use it to abort a process.
How to reproduce

This exception is raised to terminate the program when `sys.exit()` is called.

trigger — this will error
trigger — this will error
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.

Use `try...finally` to ensure cleanup on exit
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.

Catch `SystemExit` only in specific top-level cases
# 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.

Code examples
Triggerpython
import sys
sys.exit(1)  # raises SystemExit(1)
Handle in test runnerspython
try:
    run_script()
except SystemExit as e:
    print(f"Script exited with code {e.code}")
Avoid accidental exits with atexitpython
import atexit

@atexit.register
def cleanup():
    save_state()  # runs before exit even with sys.exit()
What not to do

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.

Sources
Official documentation ↗

cpython/Python/sysmodule.c

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Python errors