Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to catch SystemExit Exception in Python?
The SystemExit exception in Python is raised when the sys.exit() function is called. It is used to exit the program cleanly.
Although this exception is not an error in the traditional sense, it can be caught using a try-except block if needed, especially when you want to prevent a script from terminating abruptly.
This article explains how SystemExit works and how you can catch and handle it in Python programs.
When Does SystemExit Occur?
The SystemExit exception is raised when ?
- You call sys.exit() function to exit the program.
- The Python interpreter is terminating due to a call to exit().
Basic Example Without Handling
In the following example, we use sys.exit() function to stop the script. This will immediately terminate the program unless caught ?
import sys
print("Program is starting...")
sys.exit("Exiting the program now.")
print("This line will not be executed.")
Following is the output of the above program ?
Program is starting... Exiting the program now.
Catching SystemExit Using try-except
In this example, we catch the SystemExit exception and prevent the program from terminating. This is useful for debugging or controlling exit behavior ?
import sys
try:
print("Before calling sys.exit()")
sys.exit("Stopping execution.")
except SystemExit as e:
print("Caught SystemExit:", e)
print("Program continues after catching SystemExit.")
Following is the output obtained ?
Before calling sys.exit() Caught SystemExit: Stopping execution. Program continues after catching SystemExit.
Handling SystemExit with Exit Code
If sys.exit() function is called without any arguments, it raises a SystemExit error with a default code None. You can also pass an integer exit code ?
import sys
try:
print("Exiting with custom code...")
sys.exit(42)
except SystemExit as e:
print("Caught SystemExit with code:", e.code)
print("Exit code type:", type(e.code))
We get the output as shown below ?
Exiting with custom code... Caught SystemExit with code: 42 Exit code type: <class 'int'>
Practical Use Case
Here's a practical example showing when you might want to catch SystemExit ? to perform cleanup operations before actually exiting ?
import sys
def cleanup_function():
print("Performing cleanup operations...")
print("Files closed, connections terminated.")
def main():
try:
print("Running main application...")
# Some condition that triggers exit
if True: # Simulating exit condition
sys.exit("Application needs to exit")
except SystemExit as e:
print(f"Exit requested: {e}")
cleanup_function()
# Re-raise to actually exit
raise
main()
We get the output as shown below ?
Running main application... Exit requested: Application needs to exit Performing cleanup operations... Files closed, connections terminated. Application needs to exit
Conclusion
Use try-except to catch SystemExit when you need cleanup operations before exiting. Remember to re-raise the exception if you want the program to actually terminate after handling.
