Python SystemExit Exception

Some Python magic around sys.exit() function.

Photo by Christopher Burns on Unsplash

Recently I’ve been at the interview for one big Israel startup.
They asked me to read the code below and say what will be in the output.

  • 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.

Did you know that sys.exit(code) raises SystemExit exception?
  1. Lines 10–11 will raise an SystemExit exception

2. SystemExit exception is caught by except statement in line 12

3. Exception will be printed

4. sys.exit(1) in line 14 raises an exception

5. Code in finally statement in line 16 is executed and Out is printed out

6. And finally, the statement in line 22 is executed because of exception from sys.exit(1) and Out2 is printed


Finally

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

Exception
Out
Out2


Thanks for the attention to the topic, feel free to leave your questions in the comments for discussion.