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 try
… except
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 raisesSystemExit
- 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:
>>> 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:
>>> 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.
Related Resources
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.
For additional information on related topics, take a look at the following resources:
- Python Exceptions: An Introduction (Tutorial)
- Python's raise: Effectively Raising Exceptions in Your Code (Tutorial)
- Python's Built-in Exceptions: A Walkthrough With Examples (Quiz)
- Introduction to Python Exceptions (Course)
- Raising and Handling Python Exceptions (Course)
- Python Exceptions: An Introduction (Quiz)
- Using raise for Effective Exceptions (Course)
- Python's raise: Effectively Raising Exceptions in Your Code (Quiz)