Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Append Text or Lines to a File in Python
Next article icon

Python Systemexit Exception with Example

Last Updated : 26 Feb, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Using exceptions in Python programming is essential for managing mistakes and unforeseen circumstances. SystemExit is one example of such an exception. This article will explain what the SystemExit exception is, look at some of the situations that might cause it, and provide helpful ways to deal with it.

What is SystemExit Exception

Python has a built-in exception named SystemExit, which is triggered when the sys.exit() method is used. A SystemExit exception is triggered when the sys.exit() method is used to terminate the Python interpreter. Before the application ends, an exception may be detected and handled to carry out certain tasks.

Why does SystemExit Exception Occur?

When an intentional effort is made to use the sys.exit() method to end a Python script or application, the SystemExit exception usually arises. Below are some of the examples for SystemExit in Python:

Example 1: Explicit System Exit

In this example, a message is sent to the sys.exit() method, which raises the SystemExit exception and ends the application. The code now clearly displays the mistake.

Python3
import sys  def exit_program():     sys.exit("Exiting the program")  # Call the function instead of sys.exit directly exit_program() 

Output:

An exception has occurred, use %tb to see the full traceback.
SystemExit: Exiting the program

Example 2: Termination Signal

In this instance, the application configures a signal handler for the SIGINT signal, which is often generated by using the Ctrl+C key. The SystemExit exception is triggered upon receipt of the signal. The code now clearly displays the mistake.

Python3
import signal import time  def handler(signum, frame):     print("Received termination signal")     raise SystemExit("Exiting due to signal")  signal.signal(signal.SIGINT, handler)  try:     while True:         time.sleep(1) except KeyboardInterrupt:     print("KeyboardInterrupt received") 

Output:

An exception has occurred, use %tb to see the full traceback.
SystemExit: Exiting due to signal
/usr/local/lib/python3.10/dist-packages/IPython/core/interactiveshell.py:3561: UserWarning:
To exit: use 'exit', 'quit', or Ctrl-D.
warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)

Handle SystemExit Exception in Python

Below are some of the solution to handle SystemExit Exception in Python:

Solution 1: Catch and Log

This approach catches the SystemExit exception so that you may record the message or take care of any issues before letting the application run again.

Python3
import sys  try:     # Code that may raise SystemExit     sys.exit("Exiting the program") except SystemExit as e:     print(f"Caught SystemExit: {e}")  # Continue with the program execution if needed print("Program continues after handling SystemExit") 

Output
Caught SystemExit: Exiting the program Program continues after handling SystemExit

Solution 2: Wrap with Try-Except

By enclosing the sys.exit() call within a function, you may catch the SystemExit exception and manage it in a more polite manner.

Python3
import sys  def exit_safely(message):     try:         sys.exit(message)     except SystemExit as e:         print(f"Caught SystemExit: {e}")          # Call the function instead of sys.exit directly exit_safely("Exiting the program")  # Continue with the program execution if needed print("Program continues after handling SystemExit") 

Output
Caught SystemExit: Exiting the program Program continues after handling SystemExit

Conclusion

Writing reliable and error-tolerant programming in Python requires an understanding of the SystemExit exception. Even if it's not often seen right away, there are situations in which managing it tactfully becomes crucial. Developers may make sure the SystemExit exception is handled in a controlled way in their Python applications by being aware of the possible causes and implementing appropriate remedies.


Next Article
Append Text or Lines to a File in Python

R

rahulkatr5460
Improve
Article Tags :
  • Python
  • Python Programs
  • Python Errors
Practice Tags :
  • python

Similar Reads

  • TypeError: Unhashable Type 'Dict' Exception in Python
    In Python, the "Type Error" is an exception and is raised when an object's data type is incorrect during an operation. In this article, we will see how we can handle TypeError: Unhashable Type 'Dict' Exception in Python. What is TypeError: Unhashable Type 'Dict' Exception in PythonIn Python, certain
    4 min read
  • Print Output from Os.System in Python
    In Python, the os.system() function is often used to execute shell commands from within a script. However, capturing and printing the output of these commands can be a bit tricky. This article will guide you through the process of executing a command using os.system() and printing the resulting valu
    3 min read
  • Append Text or Lines to a File in Python
    Appending text or lines to a file is a common operation in programming, especially when you want to add new information to an existing file without overwriting its content. In Python, this task is made simple with built-in functions that allow you to open a file and append data to it. In this tutori
    3 min read
  • Python Script to Logout Computer
    As we know, Python is a popular scripting language because of its versatile features. In this article, we will write a Python script to logout a computer. Let’s start with how to logout the system with Python. To logout your computer/PC/laptop only by using a Python script, you have to use the os.sy
    2 min read
  • How to Keep a Python Script Output Window Open?
    We have the task of how to keep a Python script output window open in Python. This article will show some generally used methods of how to keep a Python script output window open in Python. Keeping a Python script output window open after execution is a common challenge, especially when running scri
    2 min read
  • Connectionerror - Try: Except Does Not Work" in Python
    Python, a versatile and powerful programming language, is widely used for developing applications ranging from web development to data analysis. However, developers often encounter challenges, one of which is the "ConnectionError - Try: Except Does Not Work." This error can be frustrating as it hind
    4 min read
  • Closing an Excel File Using Python
    We are given an excel file that is opened and our task is to close that excel file using different approaches in Python. In this article, we will explore three different approaches to Closing Excel in Python. Closing an Excel Session with PythonBelow are the possible approaches to Using Os In Python
    2 min read
  • AttributeError: __enter__ Exception in Python
    One such error that developers may encounter is the "AttributeError: enter." This error often arises in the context of using Python's context managers, which are employed with the with statement to handle resources effectively. In this article, we will see what is Python AttributeError: __enter__ in
    4 min read
  • Delete a directory or file using Python
    In this article, we will cover how to delete (remove) files and directories in Python. Python provides different methods and functions for removing files and directories. One can remove the file according to their need. Table of Content Using the os.remove() MethodDelete a FileRemove file with absol
    6 min read
  • Python Remove Set Items
    Python sets are an efficient way to store unique, unordered items. While adding items to a set is straightforward, removing items also offers a variety of methods. This article will guide you through the different techniques available to remove items from a set in Python. Remove single set item usin
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences