SystemExit

SystemExit is a built-in exception that Python raises when the sys.exit() function is called, and it’s used to terminate the Python interpreter. It inherits directly from BaseException instead of Exception, so it’s not caught by code that targets catching Exception.

When you don’t handle SystemExit, the interpreter exits without printing a traceback. You can catch it in a tryexcept block if you want to run final cleanup, but it’s generally not recommended because it could prevent your program from exiting when you’d expect it to.

SystemExit Occurs When

  • Calling sys.exit(), which raises SystemExit
  • Raising SystemExit explicitly in your code

SystemExit Can Be Used When

  • Exiting a program after completing a task
  • Terminating a script due to an error or invalid input
  • Returning a specific exit code in a command-line application

SystemExit Examples

An example of when the exception appears:

Python
>>> import sys
>>> sys.exit(0)

Calling sys.exit(0) raises a SystemExit exception and terminates the interpreter without printing a traceback.

An example of when to raise the exception:

Python
>>> import sys
>>> def check_age(age):
...     if age < 0:
...         raise SystemExit("Invalid age. Exiting.")
...     return age
...

>>> check_age(-1)
Invalid age. Exiting.

In this example, you raise SystemExit to end the program with an error message if the age is invalid.

Tutorial

Python's Built-in Exceptions: A Walkthrough With Examples

In this tutorial, you'll get to know some of the most commonly used built-in exceptions in Python. You'll learn when these exceptions can appear in your code and how to handle them. Finally, you'll learn how to raise some of these exceptions in your code.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated March 26, 2025 • Reviewed by Martin Breuss