SystemExit
SystemExit: 1
Traceback
Traceback (most recent call last):
File "main.py", line 5, in <module>
print("This won't catch SystemExit")
SystemExit: 1What causes this error
The sys.exit() function was called, or SystemExit was raised explicitly. This is the standard way to terminate a Python program with an exit code.
How to fix it
If you want to prevent program exit, catch SystemExit explicitly (not with bare `except Exception:`). For testing code that calls sys.exit(), use `pytest.raises(SystemExit)`. Check `e.code` for the exit status.
Code that causes this error
import sys
try:
sys.exit(1)
except Exception:
print("This won't catch SystemExit")Fixed code
import sys
try:
sys.exit(1)
except SystemExit as e:
print(f"Caught exit with code: {e.code}")About SystemExit
SystemExit is raised by the `sys.exit()` function. It inherits from BaseException rather than Exception, so it is not caught by `except Exception` clauses — this ensures that `sys.exit()` actually terminates the program in most cases. The exception carries an exit code: 0 or None for success, any other integer for failure.
SystemExit is the proper way to terminate a Python program from within the code. When raised without being caught, the interpreter exits with the specified code. Libraries like `argparse` raise SystemExit when the user provides `--help` or invalid arguments, and `pytest` raises it to report test results.
If you need to catch SystemExit (for testing or embedding), use `except SystemExit` explicitly. Code in finally blocks and atexit handlers still runs when SystemExit is raised.
Common scenarios
Infinite recursion from missing or incorrect base cases
Modifying dictionaries or sets during iteration
Calling generators or coroutines in unsupported ways
Using asyncio event loops incorrectly or attempting to nest them