
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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().
Example: Calling sys.exit() 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.
Example: 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.
Example: Catching SystemExit Without Exit Message
If sys.exit() function is called without any arguments, it raises a SystemExit error with a default code 0. The following example shows how to handle that -
import sys try: print("Attempting to exit with no message...") sys.exit() except SystemExit as e: print("Caught SystemExit with code:", e.code)
We get the output as shown below -
Attempting to exit with no message... Caught SystemExit with code: None