Lingua-e
Python

What is a SystemExit?

← Errors

SystemExit is raised by sys.exit() to signal that the interpreter should terminate. It is a subclass of BaseException, not Exception, so it bypasses most exception handlers. It carries an exit code that the operating system uses to report success or failure.

Why it happens

  • sys.exit() is called explicitly to terminate the program.
  • A library or framework calls sys.exit() on an unrecoverable error.
  • argparse or similar tools call sys.exit(2) when argument parsing fails.
  • Test runners catch SystemExit to report exit code without actually terminating.

Examples

Python

Code that triggers the error

import sys

def main():
    sys.exit(1)

try:
    main()
except Exception as e:
    print(f"Caught: {e}")  # never runs

Error output

# The process exits with code 1 and nothing is printed.
# SystemExit is NOT a subclass of Exception.

How to fix it

Catch SystemExit only if you need to perform cleanup or log the exit code. Use a finally block for guaranteed cleanup. If you want to return an error status from a function without exiting, raise a custom exception instead of calling sys.exit().

Fixed code

import sys

def main():
    sys.exit(1)

try:
    main()
except SystemExit as e:
    print(f"Exit called with code: {e.code}")
    # Optionally re-raise or handle cleanup here

Related errors

Ready to practice your English at work?

Lingua-e has interactive exercises built around real developer conversations: standups, code reviews, retrospectives, and more. Practice until it comes naturally.

Try Lingua-e for free