Main Menu

Python SystemExit Exception Explained

Some Pythonic thing around sys.exit() function.
So I will explain this with the help of example. Read the code below and think about what will be in the output.

1. import sys
3. def some_func():
4. …
7. def main(target):
8. try:
9. target()
10. sys.exit(0)
11. except:
12. print(“Exception Occurred”)
13. sys.exit(1)
14. finally:
15. print(“Out”)
18. try:
19. main(some_func)
20. finally:
21. print(“Out2”)

What do you think to be the output after running this code snippet?
Is it depend on the body of some_func function?

Let’s try to figure out what is going on within this small piece of code.

  1. Lines 9–10 will raise an SystemExit exception
  2. SystemExit exception is caught by except statement in line 11
  3. Exception Occurred will be printed
  4. sys.exit(1) in line 13 raises an exception
  5. Code in finally statement in line 15 is executed and Out is printed out
  6. And finally, the statement in line 21 is executed because of exception from sys.exit(1) and Out2 is printed


Now it’s easy to understand what will be printed (no matter what is going on in some_func):


Learn Python programming from scratch through Python programming certification course. This Python Course will help you master important Python programming concepts such as data & file operations in Python, object-oriented concepts in Python & various Python libraries such as Pandas, Numpy, Matplotlib, and so on. This Python certification course is also a gateway towards your Data Science career. The course is curated by industry experts which includes real-time case studies. Enroll & Get Certified now!

Drop us a Query

whatsapp arrow

Thanks for Contacting us Our representative will be in touch with you shortly