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)
Python Systemexit Exception with Example
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.